typescript 在 Angular 2 打字稿应用程序中使用 moment.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35254524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:15:55  来源:igfitidea点击:

Using moment.js in Angular 2 typescript application

typescriptangularmomentjssystemjs

提问by DanyUP

I'm struggling in using moment.js library inside an Angular 2 Typescript app. Even after reading the answer to this questionI can't get it to work.

我正在努力在 Angular 2 Typescript 应用程序中使用 moment.js 库。即使在阅读了这个问题的答案之后,我也无法让它发挥作用。

This is what I did so far:

这是我到目前为止所做的:

  • I installed moment.js using npm, so I can find the library under node_modules/moment/moment.js
  • I configured System.js to retrieve moment library:

    System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          },
          moment: {
            main: 'moment.js',
            type: 'cjs',
            defaultExtension: 'js'
          }
        },
        map: {
          moment: 'node_modules/moment'
        }
    });
    
  • I installed typescript typings with typings install moment-node --ambient --saveand typings install moment --ambient --save, so I can see the correct typings inside typings/main/ambient/moment-node and typings/main/ambient/moment
  • 我使用 npm 安装了 moment.js,所以我可以在 node_modules/moment/moment.js 下找到库
  • 我将 System.js 配置为检索矩库:

    System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          },
          moment: {
            main: 'moment.js',
            type: 'cjs',
            defaultExtension: 'js'
          }
        },
        map: {
          moment: 'node_modules/moment'
        }
    });
    
  • 我使用typings install moment-node --ambient --save和安装了打字稿类型typings install moment --ambient --save,所以我可以在typings/main/ambient/moment-node 和typings/main/ambient/moment 中看到正确的类型

Now, if in my code I use import * as moment from 'moment';typescript compilation run smooth and I can see the correct suggestion inside Atom editor (if I start with moment().I can see year(), month(), etc.). However if I run my code inside the browser, it gives an error saying that 'moment is not a function' (debugging I can see that moment is an object with lots of methods).

现在,如果在我的代码中我使用import * as moment from 'moment';typescript 编译运行顺利,我可以在 Atom 编辑器中看到正确的建议(如果我开始,moment().我可以看到 year()、month() 等)。但是,如果我在浏览器中运行我的代码,它会给出一个错误,指出“时刻不是函数”(调试我可以看到时刻是一个有很多方法的对象)。

If I write import moment from 'moment';the code in the browser runs fine, however typescript compilation fails with 'module moment has no default export' and I can't get any suggestion from Atom while writing code.

如果我import moment from 'moment';在浏览器中编写代码运行良好,但是打字稿编译失败并显示“模块时刻没有默认导出”,并且在编写代码时我无法从 Atom 获得任何建议。

What am I doing wrong? What's the correct way to import moment.js (and any non typescript library) inside an Angular 2 typescript application?

我究竟做错了什么?在 Angular 2 打字稿应用程序中导入 moment.js(和任何非打字稿库)的正确方法是什么?

采纳答案by Vladimir Trifonov

import * as moment_ from 'moment';
const moment:moment.MomentStatic = (<any>moment_)['default'] || moment_;

回答by Tony Kr?ger

As pointed out further down moment ships with its own typings now. And @angular/cli have changed aswell. Updated my answer to reflect this.

正如进一步指出的那样,moment 现在有自己的类型。@angular/cli 也发生了变化。更新了我的答案以反映这一点。

npm i --save moment

npm i --save moment

import * as moment from 'moment';

export class SomeClass implements OnInit {

  date: moment.Moment;

  ngOnInit() {
    this.date = moment();
  }

}

is all that is needed with @angular/cli.

这就是@angular/cli 所需要的。

Below is my old outdated answer.

以下是我旧的过时答案。

With angular-cli: So you get Intellisense in VsCode

使用 angular-cli:因此您可以在 VsCode 中获得 Intellisense

edit --> angular-cli-build.js

编辑 --> angular-cli-build.js

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      ...

      'moment/min/**', // add this line

      ...
    ]
  });
};

edit --> system-config.ts

编辑--> system-config.ts

const map: any = {
  moment: 'vendor/moment/min/moment.min.js' // add this line
};

In your component:

在您的组件中:

import * as moment from 'moment';

...
// example of usage
dates: moment.Moment[] = [];

ngOnInit() {
  let date = moment();
  date.add(2, 'days');
  this.dates.push(date);
}

回答by Sacky San

From your index.html add

从你的 index.html 添加

 <script src="../node_modules/moment/moment.js"></script>

In your component use:

在您的组件中使用:

declare var moment: any;
...

this.startDate = moment().subtract(15, 'days').format('DD-MM-YYYY');
this.endDate = moment().format('DD-MM-YYYY');

回答by Vladimir Trifonov

Also I found this: Install Moment.js using NPM:

我还发现了这一点:使用 NPM 安装 Moment.js:

npm install moment

Add it to your SystemJS configuration:

将其添加到您的 SystemJS 配置中:

map: {
  'angular2': 'node_modules/angular2',
  'rxjs': 'node_modules/rxjs',
  'moment': 'node_modules/moment/moment'
}

You also need the interface: tsd install moment --saveand then add:

您还需要接口: tsd install moment --save然后添加:

/// <reference path="typings/moment/moment.d.ts" />
import * as moment from 'moment';

回答by Aluan Haddad

When you import a module using namespacesyntax to gather the exports onto a single object, as in import * as moment from 'moment', you are not importing the actually moment object which the module exports, but rather all of its members. You are losing the call signature. To resolve this, in a SystemJS + TypeScript project, specify either a value of "system" for module or a value of truefor allowSyntheticDefaultImports, passing these to the TypeScript compiler, preferably via a tsconfig.jsonfile. Then import moment like so

当您使用命名空间语法导入模块以将导出收集到单个对象上时,如在 中import * as moment from 'moment',您不是导入模块导出的实际时刻对象,而是导入其所有成员。您正在丢失呼叫签名。要解决此问题,在 SystemJS + TypeScript 项目中,为模块指定“system”值或true为 allowSyntheticDefaultImports指定值,将它们传递给 TypeScript 编译器,最好通过tsconfig.json文件。然后像这样导入时刻

import moment from 'moment';

and everything will work.

一切都会好起来的。