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

编译Angular项目遇sourcemap-codec模块CommonJS语法错误,求解决

解决Angular编译时sourcemap-codec的CommonJS模块导出错误

错误说明

编译时出现以下语法错误:

SyntaxError: The requested module 'sourcemap-codec' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'sourcemap-codec';
const { decode, encode } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:98:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:137:5)
at async Loader.import (internal/modules/esm/loader.js:165:24)

有效解决方案

1. 锁定sourcemap-codec兼容版本

问题根源是sourcemap-codec的新版本(v2+)采用ESM格式,但项目依赖的部分包仍使用CommonJS的导入逻辑。通过强制安装兼容的旧版本解决:

  • npm用户:在package.json中添加overrides字段:
    "overrides": {
      "sourcemap-codec": "^1.4.8"
    }
    
  • Yarn用户:在package.json中添加resolutions字段:
    "resolutions": {
      "sourcemap-codec": "^1.4.8"
    }
    

添加后执行npm install或yarn install重新安装依赖。

2. 修复自定义代码中的导入方式

如果是项目自有代码直接导入了sourcemap-codec,按照错误提示修改导入逻辑:
原代码:

import { decode, encode } from 'sourcemap-codec';

修改为:

import pkg from 'sourcemap-codec';
const { decode, encode } = pkg;

3. 升级Node.js版本

旧版本Node.js(v12及以下)对ESM与CommonJS混合模块的支持不完善,升级到v14及以上的LTS版本,再重新编译项目。

内容的提问来源于stack exchange,提问作者Muhsin Ummer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:25:24