【发布时间】:2017-02-14 13:36:09
【问题描述】:
我是 TypeScript 的新手,我已经有一段时间没有进行任何认真的 JavaScript 开发了,所以我可能遗漏了一些明显的东西。
我正在尝试在带有 TypeScript 的 Angular 1 应用程序中使用 Moment。
我正在使用 Angular 1.6.5、Moment 2.17.1 和 TypeScript 2.17.1。我从 npm @types\angular 包中安装了 Angular 类型。 Angular 的 Intellisense 等正在 VS Code 中工作。
我已经在 GitHub 上发布了示例代码:https://github.com/kevinkuszyk/moment-angular-typescript
第一个错误
我的示例应用在浏览器中运行,但是 TypeScript 编译器抱怨它找不到 Moment:
app/controller.ts(3,20): error TS2503: Cannot find namespace 'moment'.
app/controller.ts(6,30): error TS2304: Cannot find name 'moment'.
尝试使用 /// 编译器指令
为了解决这个问题,我尝试添加以下 /// 编译器指令:
/// <reference path="../node_modules/moment/moment.d.ts" />
但这并不能修复 TypeScript 编译器:
app/controller.ts(5,20): error TS2503: Cannot find namespace 'moment'.
app/controller.ts(8,30): error TS2304: Cannot find name 'moment'.
导入时刻
接下来我尝试使用他们docs 中的说明导入 Moment:
import * as moment from 'moment';
但这会让 TypeScript 产生不同的错误:
app/controller.ts(13,5): error TS2686: 'angular' refers to a UMD global, but the current file is a module. Consider adding an import instead.
导入角度
我还导入了 Angular。这修复了 TypeScript:
import * as angular from "angular";
但现在该应用无法在浏览器中运行:
Uncaught ReferenceError: require is not defined
at controller.js:2
使用 Require.JS
最后我尝试添加 Require.JS,但这只会导致不同的运行时错误:
Uncaught Error: Module name "moment" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at makeError (require.js:168)
at Object.localRequire [as require] (require.js:1433)
at requirejs (require.js:1794)
at controller.js:2
问题
- 我在这里遗漏了什么明显的东西吗?
- 引用 npm 上的主包附带的
d.ts文件而不是单独的@types包的最佳做法是什么? - 如何在不使用外部模块加载器的情况下完成这项工作?
【问题讨论】:
-
你可以使用直接添加 moment.min.js 文件来做到这一点
-
我的
index.html已经在引用node_modules文件夹中的moment.js。如果我将其切换到moment.min.js我仍然会从 TypeScript 编译器中收到错误。 -
你能尝试像这样声明时刻变量'declare var moment: any;'在@Injectable() 或@Component 之前
-
这修复了
let foo = moment()之类的用法,但使用moment.Moment接口仍然会产生编译器错误。在此修复中,moment()的 VS Code 中也没有智能感知。 -
@KevinKuszyk 我遇到了完全相同的问题。你有想过这个吗?
标签: javascript angularjs typescript momentjs