如何导入moment.js angular2

mau*_*rok 3 npm momentjs typescript twitter-bootstrap-3 angular

我正在尝试将moment.js导入到我的angular2应用程序中.首先,我已经按照本指南,我找到了这个答案,但即使我试图按照建议的解决方案,我仍然无法导入moment.js.包存在,实际上我的IDE(visual studio)能够毫无问题地找到moment.d.ts文件,但是当我用npm start运行我的应用程序时,我在控制台中得到了这两个错误:

"NetworkError:404 Not Found - http:// localhost:3000/node_modules/moment / " / node_m...moment/错误:patchProperty/desc.set/wrapFn @ http:// localhost:3000/node_modules/zone.js /dist/zone.js:769:27 Zonehttp:// localhost:3000/node_modules/zone.js/dist/zone.js:356:24 Zonehttp:// localhost:3000/node_modules/zone.js/dist/zone .js:256:29 ZoneTask/this.invoke @ http:// localhost:3000/node_modules/zone.js/dist/zone.js:423:29
加载http:// localhost:3000/node_modules/moment时出错 "时刻"来自'我的档案'

我试图以这种方式导入时刻

import * as moment from 'moment'
Run Code Online (Sandbox Code Playgroud)

并以这种方式

import * as moment from 'moment/moment.d'
Run Code Online (Sandbox Code Playgroud)

但没什么,我仍然得到错误.我的SystemJs'map属性就是这个

 var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'services':                   'app/service',
    'moment':                     'node_modules/moment',//moment.js
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
 };
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用打字安装,我会收到此错误:

"moment"的类型已存在于"node_modules/moment/moment.d.ts"中.您应该让TypeScript解析打包的打字并卸载Typings安装的副本

所以我已经卸载它,并重新键入命令,我得到这个错误

打字ERR!message无法在注册表中找到"moment"("npm").

如何摆脱这种困境?

yur*_*zui 5

首先,通过npm安装时刻包:

npm install moment --save
Run Code Online (Sandbox Code Playgroud)

其次更改你的systemjs配置(2行):

(function (global) {
  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',
    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'moment': 'node_modules/moment', <== add this line
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line
  };
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它:

import * as moment from 'moment';
Run Code Online (Sandbox Code Playgroud)

打字将来自 node_modules/moment/moment.d.ts