【问题标题】:How to import moment.js angular2如何导入 moment.js angular2
【发布时间】:2016-11-16 04:20:53
【问题描述】:

我正在尝试将 moment.js 导入我的 angular2 应用程序。 首先我关注了这个guide,我发现了这个answer,但即使我尝试遵循建议的解决方案,我仍然无法导入moment.js。 该软件包存在,实际上我的 IDE(Visual Studio)能够毫无问题地找到 moment.d.ts 文件,但是当我使用 npm start 运行我的应用程序时,我在控制台中收到这两个错误:

“网络错误:404 未找到 - http://localhost:3000/node_modules/moment/” /node_m ...时刻/ 错误: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'

并以这种方式

import * as moment from 'moment/moment.d'

但没什么,我仍然收到错误消息。我的 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'
 };

如果我尝试使用类型进行安装,我会收到此错误:

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

所以我卸载了它,然后重新输入命令,我得到了这个错误

打字错误!消息无法在注册表中找到“moment”(“npm”)。

那么有没有办法摆脱这种困境?

【问题讨论】:

标签: angular twitter-bootstrap-3 typescript npm momentjs


【解决方案1】:

首先,通过npm安装moment包:

npm install moment --save

其次更改您的 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
  };

然后就可以使用了:

import * as moment from 'moment';

可从node_modules/moment/moment.d.ts获取打字内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2016-10-03
    • 2016-05-17
    • 2016-11-27
    • 2016-07-28
    • 1970-01-01
    • 2017-07-17
    相关资源
    最近更新 更多