Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange typescript / angular2 import behavior

I was trying to create a demo for another SO question, first with angular-cli, then with punker.

I encountered a strange behavior difference in import between the two versions.

The issue is in the second import of the following code:

moment.service.ts

import { Injectable } from '@angular/core';

// Following work in plunker setup
import m from 'moment';
// Following work in angular-cli setup
//import * as m from 'moment';

@Injectable()
export class MomentService {
  moment = m;
}

In angular-cli code, I have to use:

import * as m from 'moment';

If I use the punker setup, no matter in punker or running with local server, I have to following or it will not run in browser:

import m from 'moment';

Anyone can explain the difference in behavior??

Plunker: Link

Github: plunker code local version (include a server.js to serve locally)

Github: angular-cli version

like image 614
John Siu Avatar asked Oct 15 '16 03:10

John Siu


1 Answers

TL:DR Each demo is using a different module format. In plunker the entire module is treated as a default export. In the cli project, there is no default export.

Each demo is using a different module format. The plunker does not specify a format, I'm not sure what format systemjs uses by default, but I don't believe it is ES6. The CLI project is using the ES6 module format.

If you take a look here, you'll see when the module format is AMD, commonjs, or global, it will export the entire module as the default export. This will not happen with ES6 modules, you need to explicitly define the default export, which momentjs does not.

So, in the plunker demo, import m from 'moment' works because your configuration tells systemjs and typescript to treat the entire module as the default export if there is none. Because of the configuration in the CLI project, the module is not treated as the default export so you have to use import * as m from 'moment' which says import all named exports from moment under the namespace 'm'.

Here is a discussion on TypeScript's repo regarding this

like image 146
ryano.mcc13 Avatar answered Oct 23 '22 21:10

ryano.mcc13