Rollup打包的UI库在Webpack中出现模块未找到问题求助
解决Rollup打包UI库后MUI导入在Webpack中解析失败的问题
问题根源:你的UI库输出的ESM文件使用了不带扩展名的MUI导入路径(如@mui/icons-material/index),而严格ESM模式下要求导入必须包含完整文件扩展名,Webpack默认对node_modules里的ESM文件采用严格解析,导致无法找到模块。
以下是三种可行解决方案:
方案一:调整Webpack配置,放宽UI库的ESM解析限制
你当前的fullySpecified: false仅作用于项目自身代码(排除了node_modules),需要让Webpack对UI库也应用该规则:
全局放宽(简单直接)
修改Webpack配置的全局resolve选项:
module.exports = { entry: './src/index.js', resolve: { fullySpecified: false, }, module: { rules: [ { test: /\.(js)$/, exclude: /node_modules/, use: { loader: 'babel-loader' }, } ], } }
精准针对UI库(更安全)
仅对node_modules中的你的UI库放宽解析:
module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js)$/, exclude: /node_modules(?!\/ui-lib)/, use: { loader: 'babel-loader' }, }, { test: /\.(js)$/, include: /node_modules\/ui-lib/, resolve: { fullySpecified: false, } } ], } }
方案二:修改Rollup配置,补全MUI导入的扩展名
利用rollup-plugin-modify插件修改打包后的导入语句,添加.js扩展名:
- 安装插件:
npm install rollup-plugin-modify --save-dev
- 更新Rollup配置:
import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import typescript from "@rollup/plugin-typescript"; import replace from "@rollup/plugin-replace"; import { dts } from "rollup-plugin-dts"; import modify from 'rollup-plugin-modify'; import packageJson from "./package.json"; export default [ { input: "src/index.ts", output: [ { file: packageJson.main, format: "cjs", sourcemap: true, }, { file: packageJson.module, format: "esm", sourcemap: true, }, ], plugins: [ nodeResolve(), commonjs(), typescript({ tsconfig: "./tsconfig.json" }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), }), // 补全MUI导入的.js扩展名 modify({ find: /(from '@mui\/[^']+)(\/index)?'/, replace: '$1$2.js', }), ], external: [...Object.keys(packageJson.peerDependencies), "tss-react/mui", /@mui/], }, { input: "src/index.ts", output: [{ file: "dist/index.d.ts", format: "es" }], plugins: [dts], }, ];
方案三:调整TypeScript配置,生成带扩展名的导入
修改tsconfig.json,启用node16模块解析模式,让TypeScript编译时自动添加文件扩展名:
{ "compilerOptions": { "moduleResolution": "node16", "module": "ESNext", "target": "ESNext", // 其他现有配置... } }
注意此配置要求项目结构符合ESM规范,Rollup的TypeScript插件需正确读取该配置。
内容的提问来源于stack exchange,提问作者Muhammad Rahamni
相关产品推荐
相关产品推荐

