React + Webpack + Material UI 样式在生产中中断



我正在尝试使用 Material UI 创建一个可重用的 React 组件,并将其npm link到不同的应用程序。组件和应用程序正在使用 webpack 捆绑在一起。应用程序在开发中呈现组件很好,但是当我捆绑应用程序时,组件开始破坏 material-ui 样式。

我尝试过的一些解决方案包括:

  • https://material-ui.com/getting-启动/常见问题解答/#why-不是我的组件-在生产中正确渲染-生成
  • https://reactjs.org/warnings/invalid-hook-call-warning.html

我以为在peerDependencies中定义@material/core可以解决这个问题,但是每次我使用 Material-UI 组件时,应用程序都会抛出无效钩子调用警告。

似乎什么都不起作用 ☹️


组件的包.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上的文档,这实际上是非常有意义的:

首先,包文件夹中的 npm 链接将在全局文件夹 {prefix}/lib/node_modules/中创建一个符号链接,该符号链接链接到执行 npm link 命令的包。

请注意,该命令仅在本地创建符号链接,因此当您构建/部署时,它在逻辑上会遵循找不到包。

我的建议是为您的自定义组件创建一个作用域包。创建一个 npm 帐户,上传您的包,然后将其添加到您的项目中,如下所示:

npm install @brettoberg/reusable-component

现在,webpack 和任何其他系统应该能够找到它,因为它已经发布。

相关内容

  • 没有找到相关文章

最新更新