簡體   English   中英

在Angular和TypeScript中使用Moment

[英]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

最后,我嘗試添加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

問題

  1. 我錯過了這里明顯的東西嗎?
  2. 在npm上而不是單獨的@types包中引用主包附帶的d.ts文件的最佳實踐是什么?
  3. 如何在不使用外部模塊加載器的情況下完成這項工作?

看來這是Moment的d.ts文件的一個已知問題(請參閱問題#3763#3808#3663 )。

當我們等待正式修復時,這對我有用。

更改:

export = moment;

對此:

declare module "moment" {
    export = moment;
}

嘗試在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM