Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 both node modules.

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

like image 355
refactor Avatar asked Sep 23 '16 10:09

refactor


People also ask

What is the difference between import and require in TypeScript?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file.

What is the difference between import and require?

Require is Non-lexical, it stays where they have put the file. Import is lexical, it gets sorted to the top of the file. It can be called at any time and place in the program. It can't be called conditionally, it always run in the beginning of the file.

Can we use require in TypeScript?

TypeScript offers support for creating and using modules with a unified syntax that is similar to the ES Module syntax, while allowing the developer to output code that targets different module loaders, like Node. js (CommonJS), require.

Can I use import and require together?

Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.


1 Answers

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.

like image 71
James Monger Avatar answered Oct 06 '22 00:10

James Monger