问题描述
我创建了一个小的概念证明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.js
(webpack.common.js
和webpack.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'
}
},