Angular 14.2.7引入私有库报错:Module parse failed: Unexpected character '@'
解决Angular 14.2.7中引入@sapphire-angular/core模块的解析错误
针对你遇到的Module parse failed: Unexpected character '@'错误,以下是具体的排查和修复步骤:
1. 确认依赖安装及导入正确性
- 检查项目根目录的
package.json,确认@sapphire-angular/core已在dependencies列表中,版本无误。如果缺失,重新安装(私有库需配置正确的npm源):npm install @sapphire-angular/core - 验证
app.module.ts中的导入语句格式正确:import { SapphireButtonModule } from '@sapphire-angular/core'; @NgModule({ imports: [ // 其他模块 SapphireButtonModule ] }) export class AppModule { }
2. 调整Angular构建配置(angular.json)
Angular 14对CommonJS模块的处理有严格限制,若该库使用CommonJS格式,需在angular.json中添加允许列表:
- 找到项目下
architect > build > options,添加allowedCommonJsDependencies字段:"options": { // 原有配置 "allowedCommonJsDependencies": [ "@sapphire-angular/core" ] } - 如果库包含未编译的CSS资源,需确保Angular能正确解析:
在build > options > styles数组中添加库的CSS路径(例如node_modules/@sapphire-angular/core/styles/main.css),或在使用组件的styleUrls中单独引入。
3. 自定义Webpack配置(若上述步骤无效)
如果库的资源格式特殊(如未处理的CSS、自定义文件类型),需通过自定义Webpack加载器处理:
- 安装自定义Webpack构建器:
npm install @angular-builders/custom-webpack --save-dev - 在项目根目录创建
webpack.config.js,添加针对该库的加载规则:module.exports = { module: { rules: [ // 处理CSS文件 { test: /\.css$/, use: ['style-loader', 'css-loader'], include: /node_modules\/@sapphire-angular/ }, // 若有SCSS文件,添加对应规则 { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], include: /node_modules\/@sapphire-angular/ } ] } }; - 修改
angular.json中的构建器配置:- 将
architect > build > builder改为@angular-builders/custom-webpack:browser - 将
architect > serve > builder改为@angular-builders/custom-webpack:dev-server - 在
build > options中添加自定义Webpack配置路径:"options": { "customWebpackConfig": { "path": "./webpack.config.js" }, // 原有配置 }
- 将
4. 排查私有库本身的问题
如果以上步骤均无效,需确认私有库的打包是否符合Angular规范:
- 检查库的
package.json,确认main、module、typings字段指向正确的编译后文件 - 确保库已编译为Angular兼容的UMD或ES模块格式,未包含未处理的原始源码
内容的提问来源于stack exchange,提问作者deepo
相关产品推荐
相关产品推荐

