加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react组件化开发发布到npm

发布时间:2020-12-15 20:40:31 所属栏目:百科 来源:网络整理
导读:1.项目目录 build:webpack打包用(开发环境、发布环境) example:开发环境的模板页 lib:打包好的文件夹(用于发布到npm上) src:想要封装的公共组件 .babelrc:处理es6语法 package.json:打包的依赖文件,管理项目模块包 开发环境配置(webpack.dev.conf

1.项目目录

  • build:webpack打包用(开发环境、发布环境)
  • example:开发环境的模板页
  • lib:打包好的文件夹(用于发布到npm上)
  • src:想要封装的公共组件
  • .babelrc:处理es6语法
  • package.json:打包的依赖文件,管理项目模块包

开发环境配置(webpack.dev.config.js)

const path = require(‘path‘)
const htmlWebpackPlugin = require(‘html-webpack-plugin‘)

module.exports = {
  entry: path.join(__dirname,‘../example/main.js‘),devtool: ‘cheap-module-eval-source-map‘,output: {
    path: path.join(__dirname,‘../dist‘),filename: ‘bundle.js‘
  },plugins: [ // 插件
    new htmlWebpackPlugin({
      template: path.join(__dirname,‘../example/index.html‘),filename: ‘index.html‘
    })
  ],module: {
    rules: [
      { test: /.css$/,use: [‘style-loader‘,‘css-loader‘] },// 如果想要启用 CSS 模块化,可以为 css-loader 添加 modules 参数即可
      { test: /.scss$/,‘css-loader‘,‘sass-loader‘] },{ test: /.(jpg|png|gif|bmp|jpeg)$/,use: ‘url-loader?limit=5000‘ },{ test: /.(ttf|eot|svg|woff|woff2)$/,{ test: /.jsx?$/,use: ‘babel-loader‘,exclude: /node_modules/ }
    ]
  }
}

打包环境配置(webpack.pub.config.js)

const path = require(‘path‘)
// 导入每次删除文件夹的插件
const cleanWebpackPlugin = require(‘clean-webpack-plugin‘)
const webpack = require(‘webpack‘)
// 导入抽取CSS的插件
const ExtractTextPlugin = require("extract-text-webpack-plugin")
// 导入压缩CSS的插件
const OptimizeCssAssetsPlugin = require(‘optimize-css-assets-webpack-plugin‘)

module.exports = {
  entry:  path.join(__dirname,‘../src/index.js‘),devtool: ‘cheap-module-source-map‘,‘../lib‘),filename: ‘index.js‘,libraryTarget: ‘umd‘,//发布组件专用
    library: ‘ReactCmp‘,},plugins: [ // 插件
    new cleanWebpackPlugin([‘./lib‘]),new webpack.optimize.UglifyJsPlugin({
      compress: { // 配置压缩选项
        warnings: false // 移除警告
      }
    }),new ExtractTextPlugin("css/styles.css"),// 抽取CSS文件
    new OptimizeCssAssetsPlugin()// 压缩CSS的插件
  ],module: {
    rules: [
      {
        test: /.css$/,use: ExtractTextPlugin.extract({
          fallback: "style-loader",use: "css-loader",publicPath: ‘../‘ // 指定抽取的时候,自动为我们的路径加上 ../ 前缀
        })
      },{
        test: /.scss$/,use: ExtractTextPlugin.extract({
          fallback: ‘style-loader‘,use: [‘css-loader‘,‘sass-loader‘],use: ‘url-loader?limit=5000&name=images/[hash:8]-[name].[ext]‘ },{ test: /.js$/,exclude: /node_modules/ }
    ]
  }
}

package.json

{
  "name": "react-cmp","version": "0.0.4","description": "初始化开发react组件","main": "lib/index.js","files": [
    "build","example","src"
  ],"repository": {
    "type": "git","url": "git+https://github.com/lydxwj/react-cmp.git"
  },"homepage": "https://github.com/lydxwj/react-cmp","scripts": {
    "test": "echo "Error: no test specified" && exit 1","dev": "webpack-dev-server --config ./build/webpack.dev.config.js --open --port 3000 --hot","pub": "webpack --config ./build/webpack.pub.config.js","prepublish": "npm run pub"
  },"keywords": [ "react","component","react-cmp" ],"author": "lyd","license": "MIT","dependencies": {
    "prop-types": "^15.6.0","react": "^16.1.1","react-dom": "^16.1.1"
  },"devDependencies": {
    "babel-core": "^6.26.0","babel-loader": "^7.1.2","babel-plugin-import": "^1.6.2","babel-plugin-transform-runtime": "^6.23.0","babel-preset-env": "^1.6.1","babel-preset-react": "^6.24.1","babel-preset-stage-0": "^6.24.1","clean-webpack-plugin": "^0.1.17","css-loader": "^0.28.7","extract-text-webpack-plugin": "^3.0.2","file-loader": "^1.1.5","html-webpack-plugin": "^2.30.1","node-sass": "^4.6.0","optimize-css-assets-webpack-plugin": "^3.2.0","sass-loader": "^6.0.6","style-loader": "^0.19.0","url-loader": "^0.6.2","webpack": "^3.8.1","webpack-dev-server": "^2.9.4"
  }
}

组件

// button.js 封装的button组件
import React,{ Component } from ‘react‘;
import PropTypes from ‘prop-types‘;
export default class Button extends Component {
  constructor(props) {
    super(props)
  }
  static propTypes = {
    /**
     * @title 样式定义
     * @description 通过CSS定义按钮的样式
     */
    style: PropTypes.shape({
      color: PropTypes.string,fontSize: PropTypes.number,background: PropTypes.string,padding: PropTypes.string,}),};

  static defaultProps = {
    style: {
      color: ‘#fff‘,background: ‘green‘,padding: ‘4px‘,};
  render() {
    const style = this.props.style;
    return (
      <button style={style}>{this.props.children}</button>
    );
  }
}

// index.js输出文件
import React from ‘react‘;
import RCmp from ‘./app‘;
import Button from ‘./button‘;
import Photo from ‘./photo‘;
import ‘./app.scss‘;
RCmp.Button = Button;
RCmp.Photo = Photo;
export default RCmp;
export {
  Button,Photo,RCmp,}

实时调试

npm run dev

发布

npm run pub

将lib导入到node_modules

引入

iimport React from ‘react‘;
import PropTypes from ‘prop-types‘;
import {
  modal
} from ‘math_manage‘
import AutoSuggest from ‘react-tiny-autosuggest‘;
import MyApp,{Button,} from ‘react-cmp-master‘;

class App extends React.Component {
  static defaultProps = {}
  static propTypes = {}

  constructor(props) {
    super(props);
  }
  componentWillMount() {
    document.title = "1666";
    console.log(modal);
  }
  render() {
    const suggestions = [‘foo‘,‘bar‘];  
    const handleSelect = selection => {console.log(selection)};

    let input;
    const handleSubmit = () => console.log(input.value);
    return (
      <div> 
        <AutoSuggest
          suggestions = {suggestions}
          onSelect = {handleSelect}
          placeholder = "whatever..." 
        />
        <MyApp text=‘Hello react组件‘/>
        <Button/>
        <Photo src={‘https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2198746125,2255961738&fm=27&gp=0.jpg‘}/>
      </div>
    )
  }
}

export default App;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读