如何解决RollUp打包Material-ui时出现‘withStyles is not defined’错误
这个错误的核心原因是你的Rollup配置把@material-ui/core相关依赖标记成了外部依赖,导致打包后的代码没有包含withStyles的实现,同时运行环境也没正确提供这个变量。结合你的配置,我整理了几个关键修复点:
1. 调整外部依赖配置,避免排除@material-ui/core
你使用的external插件(看起来是rollup-plugin-node-externals)开启了includeDependencies: true,这会自动把所有node_modules里的依赖都设为外部,意味着Rollup不会把@material-ui的代码打包进你的组件。如果你的目标是打包一个可独立使用的组件包,需要把@material-ui/core从外部依赖中排除:
修改你的external插件配置:
external({ includeDependencies: true, exclude: ['@material-ui/core', '@material-ui/core/styles'] // 排除这两个包,让Rollup打包它们 })
如果你不需要自动包含所有依赖,更稳妥的方式是手动指定外部依赖(比如只把react、react-dom设为外部):
// 替换原来的external插件,直接用Rollup的external选项 external: ['react', 'react-dom'],
2. 完善babel-plugin-import配置,支持@material-ui/core/styles
当前你的babel-plugin-import只配置了@material-ui/core的组件导入,但withStyles来自@material-ui/core/styles模块,需要单独添加一个插件配置项来处理它:
在babel的plugins数组中添加:
[ 'babel-plugin-import', { libraryName: '@material-ui/core/styles', libraryDirectory: 'esm', camel2DashComponentName: false }, 'styles' // 给这个配置加个唯一名称,避免和core的配置冲突 ]
3. 确保CommonJS插件正确处理Material-UI模块
@material-ui的部分模块可能是CommonJS格式,需要让rollup-plugin-commonjs明确处理node_modules里的文件:
修改commonjs插件配置:
commonjs({ include: 'node_modules/**' // 确保所有node_modules里的CommonJS模块都被转换 })
最终修改后的rollup.conf.js关键部分示例
export default { input: 'src/index.js', output: [ { file: pkg.main, format: 'cjs', sourcemap: true }, { file: pkg.module, format: 'es', sourcemap: true }, { file: pkg.umdModule, format: 'umd', name: pkg.name, globals: { // UMD模式下指定全局依赖 react: 'React', 'react-dom': 'ReactDOM', '@material-ui/core': 'MaterialUI', '@material-ui/core/styles': 'MaterialUI.styles' } } ], // 替换原来的external插件,手动指定外部依赖 external: ['react', 'react-dom'], plugins: [ postcss({ plugins: [], minimize: true, sourceMap: 'inline' }), url(), svgr(), resolve(), babel({ presets: [ 'react-app' ], plugins: [ '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-proposal-optional-chaining', '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-class-properties', 'transform-react-remove-prop-types', [ 'babel-plugin-import', { 'libraryName': '@material-ui/core', 'libraryDirectory': 'esm', 'camel2DashComponentName': false }, 'core' ], // 新增styles模块的babel-plugin-import配置 [ 'babel-plugin-import', { 'libraryName': '@material-ui/core/styles', 'libraryDirectory': 'esm', 'camel2DashComponentName': false }, 'styles' ] ], exclude: 'node_modules/**', runtimeHelpers: true }), replace({ 'process.env.NODE_ENV': JSON.stringify('production') }), commonjs({ include: 'node_modules/**' }), terser() ] }
这样修改后,Rollup会正确打包withStyles的代码,或者在UMD模式下正确关联全局变量,解决"withStyles is not defined"的错误。
内容的提问来源于stack exchange,提问作者Zero

