You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Material UI构建设计系统包时模块导入失败的解决方案咨询

Material UI设计系统包导入模块解析失败问题

问题详情

我们正在将基于Material UI的设计系统打包为可跨项目复用的npm包,构建过程无报错,但在其他项目中安装并导入该包时,出现模块解析错误:

ERROR in ../design-system/dist/main.js 5:0-54
Module not found: Error: Can't resolve '@mui/material/Tab' in '/Users/***/***/minimal-example/frontends/design-system/dist'
Did you mean 'index.js'?
BREAKING CHANGE: The request '@mui/material/Tab' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains ""type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

复现步骤

已准备最小复现项目,步骤如下:

  • 进入design-system目录,执行:
    npm ci
    npm run build
    
  • 进入package目录,执行:
    npm ci
    npm start
    

解决方案

1. 调整设计系统的打包配置(推荐)

错误根源是ES模块严格模式要求导入路径必须包含完整文件扩展名。针对webpack打包的设计系统,可做如下配置:

方法A:webpack直接配置扩展名解析

在design-system/webpack.config.js中添加/修改:

module.exports = {
  // ...其他已有配置
  output: {
    // ...
    environment: {
      module: true, // 确保输出符合ES模块规范
    },
  },
  resolve: {
    extensions: ['.js', '.jsx'], // 自动解析这些扩展名
  },
};

方法B:用Babel插件自动补全扩展名

安装babel-plugin-add-import-extension:

npm install babel-plugin-add-import-extension --save-dev

然后在babel.config.json中配置:

{
  "plugins": [
    ["add-import-extension", { "extension": "js" }]
  ]
}

2. 调整设计系统的模块类型

如果设计系统的package.json中设置了"type": "module",可尝试移除该字段,切换到CommonJS模式,绕过ES模块的严格解析限制。注意:此方法可能影响项目对ES模块特性的支持,需根据实际情况评估。

3. 在消费项目中配置webpack解析规则

若无法修改设计系统的配置,可在消费项目(package目录)的webpack配置中添加扩展名解析:

module.exports = {
  resolve: {
    extensions: ['.js', '.jsx'],
  },
};

内容的提问来源于stack exchange,提问作者Antonio Gamiz Delgado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:02:25