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

Angular1.6集成Angular-Moment-Picker遇Moment is not defined错误求助

解决Angular 1.6中Angular-Moment-Picker的「Moment is not defined」错误

你遇到的问题核心是angular-moment-picker依赖全局作用域下的moment对象,但当前配置没正确把moment暴露给它,另外还有个小错误:把非Angular模块的moment加到了Angular的依赖数组里,这也会干扰模块加载逻辑。下面一步步给你解决:

1. 修正Angular模块依赖的错误

首先,moment本身不是Angular模块,你不能把它放到angular.module的依赖数组里,这是无效操作。你的app.module.js里应该只保留momentPicker作为依赖:

import momentPicker from 'angular-moment-picker';
import * as moment from 'moment/min/moment-with-locales';

// 移除依赖数组里的moment,只保留momentPicker
const app = angular.module('app', [/* 你的其他依赖 */, momentPicker]);

2. 强制把moment挂载到全局window对象

angular-moment-picker初始化时会直接查找全局的moment变量,但ES模块的导入默认是局部作用域的,所以你需要手动把moment挂到window上:

import * as moment from 'moment/min/moment-with-locales';
// 将moment暴露到全局作用域
window.moment = moment;

3. 优化Webpack配置(可选但推荐)

如果你想用Webpack的ProvidePlugin自动注入moment,需要调整配置确保它能被全局访问到。修改你的webpack-config.js:

new webpack.ProvidePlugin({
  moment: 'moment/min/moment-with-locales',
  // 额外添加这行,确保moment被挂载到window
  'window.moment': 'moment/min/moment-with-locales'
}),

配置后,你甚至可以不用在app.module.js里手动import moment,但如果需要设置语言 locale,还是要手动导入后配置:

import * as moment from 'moment/min/moment-with-locales';
moment.locale('zh-cn'); // 示例:设置中文语言环境
window.moment = moment;

4. 验证版本兼容性

确认你安装的angular-moment-picker版本和Angular 1.6、moment版本兼容,建议查看angular-moment-picker的package.json里的peerDependencies,避免版本冲突。可以尝试重新安装依赖:

npm uninstall angular-moment-picker moment
npm install angular-moment-picker moment@2.29.4 # 选择一个和插件兼容的moment版本

按照上面的步骤调整后,应该就能解决「Moment is not defined」的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:14:01