Use external Typescript Library in Angular2 (e.g.

2019-06-04 05:54发布

i am new to the Angular2 World (and JS/TS). So far, i did find all answers to my questions on the web (mainly on stackoverflow). But i fail to get angular2-moment to work.

I did follow the instructions on The angular2-Moment GitHub-Page, but i get the following error the moment my app loads:

angular2-polyfills.js:127 GET http://localhost:8080/angular2-moment 404 (Not Found)
http://localhost:8080/angular2-moment(…)

Webstrom did the import as: import {DateFormatPipe} from "angular2-moment/index";

I tried to change this to: import {DateFormatPipe} from "angular2-moment";, import {DateFormatPipe} from "angular2-moment/DateFormatPipe"; or import {DateFormatPipe} from "angular2-moment/DateFormatPipe.js"; but this does not help.

If i change the import to import {DateFormatPipe} from "node_modules/angular2-moment/DateFormatPipe.js"; i get the following error:

GET http://localhost:8080/moment 404 (Not Found)
http://localhost:8080/moment(…)

I dont know what i am doing wrong, could use some help here. Thanks a lot for your help!

I use the angular2-rc and want to use it like this:

@Component({
selector: ...,
template: ...,
pipes: [DateFormatPipe]

})

EDIT: Thanks to @Sasxa I was able to solve my problem. But I still had to figure it out a little, so i will post my exact solution. I changed my system.config.js to:

....
var map = {
    'app':                          'build/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/moment.js', //<--this
    'angular2-moment':              'node_modules/angular2-moment' //<--this
};
// 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' },
    'angular2-moment':              { defaultExtension: 'js' }//<--this
};
...

Btw: the right import as import {DateFormatPipe} from "angular2-moment/index"; indeed works.

1条回答
Viruses.
2楼-- · 2019-06-04 06:18

You need to configure your module loader (I assume it's SystemJS) to recognize the moment library. Take a look at their plunker example, config.js specifically. You'll need to add something similar to:

System.config({
  map: {
    'moment': 'path/to/moment/library'
    'angular2-moment': 'path/to/angular2-moment/library'
  }
});

and maybe set System.config.package too, if default configuration doesn't work...

查看更多
登录 后发表回答