我正在尝试使用 Material UI 创建一个可重用的 React 组件,并将其 npm link
到另一个应用程序。组件和应用程序使用 webpack 进行捆绑。该应用程序在开发中很好地渲染了组件,但是当我捆绑该应用程序时,该组件开始破坏 Material-ui 样式。
我尝试过的一些解决方案包括:
- https://material-ui.com/getting-started/faq/#why-arent-my-components-rendering-correctly-in-production-builds
- https://reactjs.org/warnings/invalid-hook-call-warning.html
我认为在 peerDependency
中定义 @material/core
可以解决这个问题,但每次我使用 Material-UI 组件时,应用程序都会抛出 Invalid Hook Call Warning .
似乎没什么作用☹️
<小时/>组件的package.json:
{
"name": "component",
"version": "1.0.0",
"description": "",
"main": "build/index.js",
"scripts": {
"test": "jest",
"start": "webpack --watch",
"build": "webpack --optimize-minimize -p",
"dist": "npm run build"
},
"peerDependencies": {
"@material-ui/core": "^3.2.0 || ^4.0.0",
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.5.0",
"@babel/preset-env": "^7.5.4",
"@babel/preset-react": "^7.0.0",
"@material-ui/core": "^4.9.0",
"@material-ui/icons": "^3.0.2",
"babel-cli": "^6.26.0",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.5",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-runtime": "^6.26.0",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.7.0",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.1.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.7.0",
"faker": "^4.1.0",
"husky": "^1.3.1",
"jest": "^23.6.0",
"jest-styled-components": "^6.3.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"sinon": "^7.2.2",
"webpack": "^4.39.2",
"webpack-cli": "^3.3.7"
},
"dependencies": {
"clsx": "^1.0.4",
"prop-types": "^15.6.2"
}
}
组件的webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.jsx',
mode: 'production',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/env'],
},
},
},
],
},
resolve: { extensions: ['*', '.js', '.jsx'] },
externals: {
react: 'react',
},
optimization: {
minimize: true,
},
};
任何帮助将不胜感激!提前致谢。
最佳答案
如果您查看 npm link
上的文档,这实际上非常有意义。 :
First, npm link in a package folder will create a symlink in the global folder {prefix}/lib/node_modules/ that links to the package where the npm link command was executed.
请注意,该命令仅在本地创建符号链接(symbolic link),因此当您构建/部署时,它在逻辑上会遵循无法找到的包。
我的建议是创建一个 scoped package为您的自定义组件。创建一个 npm 帐户,上传您的包,然后将其添加到您的项目中,如下所示:
npm install @brettoberg/reusable-component
现在,webpack 和任何其他系统应该能够找到它,因为它已发布。
关于node.js - React + Webpack + Material UI 样式在生产中的突破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59884669/