Angular 8导入ngx-chips 2.0.0-beta.0报非ECMAScript模块导入错误
问题背景
在Angular 8项目中导入ngx-chips@^2.0.0-beta.0时触发编译报错,项目已手动安装ng2-material-dropdown@0.10.1依赖。
报错信息
ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 644:36-48 Can't import the named export 'CommonModule' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 649:12-24 Can't import the named export 'CommonModule' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 667:24-36 Can't import the named export 'CommonModule' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 31:18-27 Can't import the named export 'Component' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 219:18-27 Can't import the named export 'Component' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 458:18-27 Can't import the named export 'Component' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 606:18-27 Can't import the named export 'Component' from non EcmaScript module (only default export is available) ERROR in ./node_modules/ngx-chips/node_modules/ng2-material-dropdown/fesm2015/ng2-material-dropdown.mjs 618:22-34 Can't import the named export 'ContentChild' from non EcmaScript module (only default export is available)
错误原因
核心触发逻辑:ngx-chips@2.0.0-beta.0为测试版本,其嵌套依赖的高版本ng2-material-dropdown采用.mjs格式的ES Module规范输出,Angular 8配套的Webpack 4构建链默认不支持从这类混合模块格式的文件中导入具名导出(如CommonModule、Component等Angular API);同时项目中手动安装的ng2-material-dropdown@0.10.1与ngx-chips嵌套的依赖版本不一致,构建时会优先加载嵌套目录下的不兼容版本文件,最终触发编译报错。
解决方案
优先选择第一种方案,稳定性最高,适配生产环境使用:
方案1:更换为Angular 8兼容的ngx-chips稳定版本
- 卸载现有不兼容版本,执行命令:
npm uninstall ngx-chips --save - 安装适配Angular 8的稳定版,执行命令:
npm install ngx-chips@1.9.8 --save - 正常在业务模块中导入
TagInputModule即可,不会再出现模块格式兼容问题。
- 卸载现有不兼容版本,执行命令:
方案2:强制统一ng2-material-dropdown依赖版本(如需保留2.0.0-beta.0版本)
- 打开项目根目录的
package.json文件,在与dependencies、devDependencies平级的位置添加依赖强制解析配置:- 使用npm作为包管理器时添加:
"overrides": { "ng2-material-dropdown": "0.10.1" }- 使用yarn作为包管理器时添加:
"resolutions": { "ng2-material-dropdown": "0.10.1" } - 删除项目根目录下的
node_modules文件夹、锁文件(npm对应package-lock.json,yarn对应yarn.lock) - 重新执行
npm install或yarn install安装依赖,重启构建服务即可恢复正常编译。
- 打开项目根目录的
内容的提问来源于stack exchange,提问作者VenkateshW
相关产品推荐
相关产品推荐

