繁体   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