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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With