跟我一起写一个hello-world react组件并发布到npm

第一步:初始化我们的配置

$ mkdir react-hello-world
$ cd react-hello-world/
$ npm init -y

修改我们的package.json文件

//package.json
{
  "name": "react-hello-world",
  "version": "1.0.0",
  "description": "",
  "main": "dist/bundle.js",
  "files": [
    "dist"
  ],
 "scripts": {
    "build": "webpack --env.NODE_ENV=production",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

接下来安装相关依赖

npm i react react-dom
npm i -D  babel-loader @babel/core @babel/preset-env @babel/preset-react webpack webpack-dev-server webpack-cli html-webpack-plugin webpack-node-externals css-loader style-loader 

接下来配置 webpack。这里分成两份配置,一份用于开发环境(development),一份用于单独打包组件用于生产环境(production)。
在开发环境下,我们需要搭建一个完整的项目,让我们可以开发组件,并可以将其引入其他组件,渲染到浏览器中看到效果。
同时我们也需要一些开发工具的支持,比如 HMR(hot module reloa) 组件热更新和详细的报错信息。
在生产环境下,只需要打包组件本身,不包括工程里面的其他组件。同时我们需要压缩文件体积,尽量减小组件打包之后的体积。
Webpack 配置
下面是我们的 webpack 开发配置

//dev.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, '../dist'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  devServer: {
    contentBase: './dist'
  },
  plugins: [
    new htmlWebpackPlugin({
      template: 'public/index.html'
    })
  ],
};
//prod.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  mode: 'production',
  entry: './src/helloWorld.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, '../dist'),
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  externals: [nodeExternals()]
};
//webpack.config.js
module.exports = (env) => {
  if (env && env.NODE_ENV === 'production') {
    return require('./webpack/prod.config.js');
  } else {
    return require('./webpack/dev.config.js');
  }
}
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}
//public/index.html
<!DOCTYPE html>
<html>
  <body>
    <div id="app" />
  </body>
</html>

完成以上配置以后,我们可以在 src 文件夹里面开发自己组件。
src内的内容如下

//app.js
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './HelloWorld';
ReactDOM.render(<HelloWorld/>,document.getElementById('app'));
//helloWorld.css
.hello-world {
    font-size: 40px;
    background-image: -webkit-gradient(linear, left 0, right 0, from(rgb(4, 94, 170)), to(rgb(1, 152, 216)));
    -webkit-background-clip: text; /*必需加前缀 -webkit- 才支持这个text值 */
    -webkit-text-fill-color: transparent; /*text-fill-color会覆盖color所定义的字体颜色: */
    font-weight: bold;
}
//HelloWorld.js
import React,{ Component } from 'react';
import './HelloWorld.css';
class HelloWorld extends Component{
    constructor(props){
        super(props);
        this.state={
            value:'HelloWorld'
        }
    }
    render(){
        const { value } = this.state;
        return(
            <div className="hello-world">
                {value}
            </div>
            )
    }
}
export default HelloWorld;
//index.js
import HelloWorld from './HelloWorld';
export default HelloWorld;

运行 npm run dev,让 webpack-dev-server 渲染到浏览器中,实时看到效果

打包并验证
打包组件,只需要运行 npm run build 就可以了。
接下来可以通过 npm link 把打包之后的组件引入到 global node_modules 中,然后在验证 demo 中再通过 npm link HelloWorld 引入这个组件,并验证是否符合预期。
接下来 demo 里面就可以直接 “import HelloWorld from ''react-hello-world”
组件发布到npm是:npm publish
我使用npm publish发包发现并没有发布,这个是要登录npm.org进行注册

使用npm publish进行发布

上面是我遇到的一个报错,说明hello-world组件已经被注册过了,我得选一个没有人发布的名字呢
下面是发布成功的标志

可以在npm上面搜到react-hello-dimple
24小时之后才能够搜到我呢

关于撤销包和删除包博客:https://www.cnblogs.com/penghuwan/p/6973702.html#_label3_0
关于发包博客:https://www.jianshu.com/p/db6113c94dbc
关于发包博客:https://blog.csdn.net/qq_24956515/article/details/80514262

猜你喜欢

转载自www.cnblogs.com/smart-girl/p/10731183.html