[英]Using Moment with Angular and TypeScript
我是TypeScript的新手,自從我進行了認真的JavaScript開發以來已經有一段時間了,所以我可能會遺漏一些明顯的東西。
我正在嘗試在帶有TypeScript的Angular 1應用程序中使用Moment。
我正在使用Angular 1.6.5,Moment 2.17.1和TypeScript 2.17.1。 我從npm @types\\angular
軟件包安裝了Angular @types\\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'.
接下來,我嘗試根據其文檔中的說明導入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,但這只會導致另一個運行時錯誤:
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
@types
包中引用主包附帶的d.ts
文件的最佳實踐是什么? 嘗試在tsconfig.json
文件中將@types
作用域包明確聲明為@types
:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false,
"typeRoots": [
"./node_modules/@types"
]
}
}
確保類型定義已正確安裝在node_modules/@types/...
,並且您的TypeScript編譯器是最新的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.