This article mainly introduces the use of native ES module method parsing in Node.js, as well as links to some content. Let’s take a look at it together. Friends in need can refer to it.
Starting from version 8.5.0, Node.js supports native ES modules, which can be turned on through command line options. The new features are largely due to Bradley Farias.
1. Demonstration
The code directory structure of this example is as follows:
esm-demo/ lib.mjs main.mjs
lib.mjs:
export function add(x, y) { return x + y; }
main.mjs:
import {add} from './lib.mjs'; console.log('Result: '+add(2, 3));
Run the demo:
$ node --experimental-modules main.mjs Result: 5
2. Checklist: Things to note
ES Module:
·You cannot dynamically import modules. However, work on dynamic import() is in progress and support should be available soon.
·There are no meta variables such as __dirname and __filename. However, there is a proposal for a similar function: "import.meta". It might look like this:
console.log(import.meta.url);
·Now all module identifiers are URLs (this part is new in Node.js):
· File - Relative path with file extension: ../util/tools.mjs
##· Library - no file extension and no path lodash
· It remains to be seen how better to make the npm library also available in the browser (without using bundler). One possibility is to introduce RequireJS-style configuration data that maps paths to actual paths. Currently, it is illegal to use bare path module identifiers in browsers.
Interoperability with CJS modules
import fs1 from 'fs'; console.log(Object.keys(fs1).length); // 86 import * as fs2 from 'fs'; console.log(Object.keys(fs2)); // ['default']
· Require() cannot be used in ES modules. The main reason is:
· Path resolution works slightly differently: ESM does not support NODE_PATH and require.extensions. Also, the fact that its identifier is always a URL causes some slight differences.
· ES modules are always loaded asynchronously, which ensures maximum compatibility with the web. This loading style cannot be mixed with synchronous loading of CJS modules via require().
· Disabling synchronous module loading can also preserve the fallback path for Top-level await imported ES modules (a feature currently under consideration).
3. ES modules on earlier versions of Node.js
FAQ
When can I use ES modules without command line options?
Further reading
· “Making transpiled ES modules more spec-compliant” [using ES modules natively vs. transpiling them via Babel]
· “Module specifiers: what's new with ES modules?” [Why .mjs? How are module specifiers resolved? Etc.]
· “Modules” [in-depth chapter on ES modules in “Exploring ES6”]
· Blog: “ES proposal: import() – dynamically importing ES modules”
· Proposal: “import.meta”
The above is the detailed content of Introducing using native ES modules in Node.js. For more information, please follow other related articles on the PHP Chinese website!