Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rollup for Angular 2's AoT compiler and importing Moment.js

I'm trying to follow the official AoT guide for Angular 2, and I'm using Moment.js in my application. Moment.js is on my packages.json file, and I'm using version 2.15.0. I've been importing it like this so far:

import * as moment from 'moment'; 

But when I get to the part where I have to run rollup, I end up with the following error:

Cannot call a namespace ('moment')

Which appears to be related to the way I import moment according to this. So, how am I supposed to do this? I can't seem to import moment any other way. If I use

import moment from 'moment' 

I get the compile error

External module ''moment'' has no default export

like image 817
Vitor Machado Avatar asked Sep 15 '16 20:09

Vitor Machado


2 Answers

I have finally managed to get rid of both errors. Indeed to avoid:

Cannot call a namespace ('moment')

You need to use:

import moment from 'moment'

Then to avoid

"moment" has no default export

You have to add into your tsconfig.json (compilerOptions):

"allowSyntheticDefaultImports": true

EDIT 17/11/2016

I also had to add the following to my rollup-config.js file:

plugins: [   nodeResolve({jsnext: true, module: true}),   commonjs({     include: [         'node_modules/rxjs/**',         'node_modules/moment/**'       ]     }   }),   uglify() ] 
like image 183
j3r6me Avatar answered Sep 28 '22 11:09

j3r6me


I found a nice solution for the problem at hand:

Npm-install additional package moment-es6 which provides a default export. Then import from 'moment-es6' instead of from 'moment':

import moment from 'moment-es6';

  • For use with systemjs, add the following to the systemjs.config.js map section:
    'moment-es6': 'npm:moment-es6/index.js'

  • add 'node_modules/moment-es6/**' to the include's of your rollup configs commonjs section (rollup-plugin-commonjs)

like image 21
akaegi Avatar answered Sep 28 '22 13:09

akaegi