微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Webpack将React组件构建为依赖库?

如何解决如何使用Webpack将React组件构建为依赖库?

我创建了一个小的概念证明React组件并将其推送到此处-> https://github.com/lropero/poc

我希望能够通过执行以下操作将这个组件导入另一个React项目中:npm install git+https://github.com/lropero/poc.git然后是import Poc from 'poc',并能够渲染该组件(即<Poc />)。事情是我收到React的不变违反错误#321 ,因为我正在使用钩子(在此示例中为useEffect)。我尝试注释掉此挂钩,然后可以看到<p>TEST</p>元素呈现良好。我猜这是构建Poc捆绑包时的Webpack问题吗?

相关文件如下所示(所有内容https://github.com/lropero/poc):

./src/index.jsx

import React,{ useEffect } from 'react'
import ReactDOM from 'react-dom'

const App = () => {
  useEffect(() => {
    console.log('SUCCESS')
  },[])
  return <p>TEST</p>
}

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
  ReactDOM.render(<App />,document.getElementById('app'))
}

export default App

./package.json

{
  "name": "poc","version": "0.1.0","description": "Proof of concept importing React bundle.","module": "./dist/bundle.js","scripts": {
    "build": "rm -rf dist && npx webpack --config webpack.prod.js","clean": "rm -f npm-*.log && rm -f package-lock.json && rm -rf node_modules && npm cache verify","nuke": "npm run clean && npm install","start": "npx webpack-dev-server --config webpack.dev.js"
  },"devDependencies": {
    "@babel/core": "^7.11.6","@babel/plugin-transform-runtime": "^7.11.5","@babel/preset-env": "^7.11.5","@babel/preset-react": "^7.10.4","babel-loader": "^8.1.0","html-webpack-plugin": "^4.4.1","react": "^16.12.0","react-dom": "^16.12.0","source-map-loader": "^1.1.0","webpack": "^4.44.2","webpack-cli": "^3.3.12","webpack-dev-server": "^3.11.0","webpack-merge": "^5.1.4"
  },"peerDependencies": {
    "react": "^16.12.0","react-dom": "^16.12.0"
  },"license": "UNLICENSED","private": true
}

./webpack.config.jswebpack.common.jswebpack.prod.js合并在一起):

{
  entry: './src/index.jsx',mode: 'production',module: {
    rules: [
      {
        test: /\.jsx?$/,exclude: path.resolve(__dirname,'node_modules'),use: [
          {
            loader: 'babel-loader',options: {
              presets: ['@babel/preset-env','@babel/preset-react']
            }
          }
        ]
      }
    ]
  },output: {
    filename: 'bundle.js',library: 'Poc',libraryTarget: 'umd',path: path.resolve(__dirname,'dist')
  },resolve: {
    alias: {
      [name]: path.resolve(__dirname,'src')
    },extensions: ['.js','.jsx']
  }
}

解决方法

使用生产模式进行构建时,您似乎忘记了将React + ReactDOM从捆绑文件中排除。

在将代码发布为React组件时,除了将React设置为对等依赖项之外,还必须将react设置为外部对象才能在消费者库中使用react。

在您的webpack.prod.js中添加更多外部资源:

externals: {
  'react': {
    commonjs: 'react',commonjs2: 'react',amd: 'React',root: 'React'
  },'react-dom': {
    commonjs: 'react-dom',commonjs2: 'react-dom',amd: 'ReactDOM',root: 'ReactDOM'
  }    
},

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。