CleanCrispCode CleanCrispCode - 1 year ago 162
Node.js Question

Importing modules in Angular2

As per understanding , Node js uses CommonJS module pattern , and in CommonJS
pattern we use require() to import a node module.

In Angular 2 application development we use @angular/core , @angular/common etc
node modules.

My question is:

Why do we use "import {} from '@angular/core'"[which is ES6 module syntax]
instead of commonJS require() syntax for accessing node modules
in angular2 code files.

Answer Source

The reason for this, is that Angular2 is written in TypeScript.

TypeScript is a superset of ES2015, and wants to be as close to ES2015 suggested syntax as possible. That's why you use the ES2015 import {} from syntax.

However, TypeScript also comes with a built-in transpiler (tsc). Meaning you write TypeScript code, but target a specific EcmaScript version in your tsconfig.json

  • When targetting ES5 and looking into the transpiled code, you will clearly see that behind the scenes TypeScript will translate import {} from to require()in the transpiled files.
  • When targetting ES6, of course in the transpiled code, your imports will be ES2015 imports. Be aware that when targetting ES6, you will need babel to transpile your ES6 modules to ES5 or use System.js to load your ES6 modules in the browser.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download