Angular 12升级至13时Moment.js构建警告问题求助
Angular 13 升级后 Moment.js 构建警告(指定 en 语言包时)的解决方案
1. 调整 ContextReplacementPlugin 配置语法
Angular 13 适配的 Webpack 版本对 ContextReplacementPlugin 的匹配逻辑有细节变化,检查并修改你的自定义 Webpack 配置:
const webpack = require('webpack'); module.exports = { plugins: [ new webpack.ContextReplacementPlugin( /moment[\/\\]locale$/, /^en$/ // 确保正则精准匹配 en 语言包,避免模糊匹配导致的警告 ) ] };
如果仍有问题,尝试用绝对路径指向 moment 的 locale 目录(比如 path.resolve(__dirname, 'node_modules/moment/locale'))替换正则的第一参数。
2. 手动导入指定语言包替代插件配置
直接在项目入口文件(如 main.ts)中手动导入 en 语言包,跳过插件的上下文替换逻辑:
import 'moment/locale/en';
同时确保项目中没有其他代码自动导入所有语言包。
3. 升级 Moment.js 版本
你当前使用的 moment@2.24.0 版本较旧,存在与 Webpack 5/Angular 13 的兼容性问题,升级到最新 2.x 版本:
npm update moment --save # 或使用 yarn yarn upgrade moment@latest
4. 完善 tsconfig.json 配置
除了 allowSyntheticDefaultImports,开启 esModuleInterop 确保 CommonJS 模块(如 Moment.js)能在 ES 模块环境下正确导入:
{ "compilerOptions": { "esModuleInterop": true, "allowSyntheticDefaultImports": true, // 其他原有配置... } }
5. 清理构建缓存
Angular 13 的构建缓存可能残留旧配置,执行清理后重新构建:
ng cache clean ng build
内容的提问来源于stack exchange,提问作者Idris
相关产品推荐
相关产品推荐

