CleanCrispCode CleanCrispCode - 2 months ago 25
TypeScript Question

Import vs Require in Typescript

While I was going through Angular2 documentation ,I came
across below code in here.

src/polyfills.ts

import 'core-js/es6';
import 'core-js/es7/reflect';
require('zone.js/dist/zone');

if (process.env.ENV === 'production') {
// Production
} else {
// Development
Error['stackTraceLimit'] = Infinity;
require('zone.js/dist/long-stack-trace-zone');
}


In the above code we can see that there are both "import" and require statements.
"core-js" and "zone.js" are node modules.

My question why was "import" used for core-js and "require" for "zone.js", is there any specific reason for this.

Answer

With TypeScript, import can be used if there is a declaration file (see Declaration Files in basarat's book) for the module.

If there isn't a declaration file, the TypeScript compiler doesn't know if the module exists, so you need to use require instead which lacks the compilation checking.