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

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加载器处理:

  1. 安装自定义Webpack构建器:
    npm install @angular-builders/custom-webpack --save-dev
    
  2. 在项目根目录创建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/
          }
        ]
      }
    };
    
  3. 修改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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:25:18