You might sometimes see import * from library
in the third-party library or some project, and in the meantime, you can also see this code import something = require('library').
Would you wonder what the difference between these two sentences is? Here is the explanation about what difference between import from
and import require
is.
Let’s see an example first, and you can find these two usages:
1 | import uuid = require('uuid'); |
And, another way like this:
1 | import uuid from 'uuid'; |
Here comes a question: is there any difference between these two ways? Or, put it in another word: which way is correct to use? Let’s check the fundamental difference between these two ways first.
import from | import require |
---|---|
Static estimation | Dynamic estimation |
Compile-time error | Runtime error |
You might know CommonJS
and ESM.
Those two are the JavaScript format spec. In the CommonJS, it involves a Module
concept. After CommonJS, ESM introduces the import/export
concept and does the performance tuning for this concept. Let’s see CommonJS way first:
module.js
1 | module.exports = { |
app.js
1 | var module = require('module') |
In the CommonJS, it uses module.exports
to export resources to outside callers. Then how does the ESM do?
module.js
1 | export foo function(){} |
app.js
1 | import { foo, bar } from 'module' |
If you use require, the compiler changes to the exported module as followed format:
1 | function (exports, require, module, __filename, __dirname) { |
And then, when you are running the code:
1 | const module = { exports: {} } |
After this, you can get the module variables, so you can see what things the require
does are:
- Resolution -> get the real path of the module.
- Loading -> load module.
- Wrapping -> encapsulate the module.
- Evaluation -> VM does this for running the module.
- Caching -> reuse of this module.
That’s the reason why require means runtime linking, but ESM does that in compile-time.
In the TypeScript, it supports this:
1 | import uuid = require('uuid'); |
But it recommends that you can use this way:
1 | import * as uuid from 'uuid'; |
These two are equivalent.
Happy coding, enjoy.
Reference