angular - 如何导入 moment.js angular2

标签 angular twitter-bootstrap-3 typescript npm momentjs

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

"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/" /node_m...moment/ Error: 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
Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'

我试过用这种方式导入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'
 };

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

Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings

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

typings ERR! message Unable to find "moment" ("npm") in the registry.

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

最佳答案

首先,通过 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

中可用

关于angular - 如何导入 moment.js angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38354048/

相关文章:

javascript - Angular RoutereuseStrategy,如何仅从特定路由重用?

javascript - Angular 4 : Subscribing to Observable

css - 如何使 Bootstrap 导航栏居中

jQuery:一次只展开一个面板

twitter-bootstrap - Bootstrap 3 导航栏折叠

typescript - Nest 无法解决对循环依赖的服务依赖

typescript - TypeScript 支持 TouchEvent 吗?

angular - Angular "strict-origin-when-cross-origin"错误是什么意思?

node.js - 如何使用 angular-cli 加载包?

typescript - Angular 2 子路由卡住应用程序