Home > Article > Web Front-end > A brief analysis of how to use import syntax in node
node.js supports import syntax. It is a simple knowledge point, but it can remind us to get out of knowledge misunderstandings, pay more attention to the outside world of knowledge, and constantly open up the boundaries of our own knowledge.
The mainstream front-end modularization specifications currently include the following:
Therefore, there are two mainstream specifications CommonJS
and ESM
, but because Node.js does not support ESM
Standards often lead to the coexistence of two standard codes in our projects, resulting in the following situation:
// 在node端执行构建的时候 const _ = require('loadsh') // 在浏览器端实现的时候 import _ from 'loadsh';
In this way, pain points are easy to occur in development, and often our solutions The solution is to use various construction tools to solve the problem, such as: webpack
vite
. Especially when we write node.js compilation scripts in projects, we often need to switch. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
But after the Node.js V14 version, it begins to support the ESM specification. You can directly Syntax such as import
export
is used in Node.js. I have finally waited for this day?
PS: In fact, this feature has been added as early as Node.js V8.5 version, but it has always been necessary to turn on this feature through the global variable –experimental-modules
, because it is not Stability is not turned on in most projects, but since 16, we can boldly use it in projects, but some old projects recommend not turning it on for the time being.
Let’s first read the relevant instructions from the official website:
Through the above we can know several usage methods:Node.js has two module specifications:
CommonJS
Module Specification andECMAScript
Module Specification Developers can settype=module
ornode xxx.js --input-type# through the
.mjsfile extension,
package.jsonThe ## flag tells Node.js to use the
ECMAScriptspecification to execute code. Without these settings, Node.js will use
CommonJSfor execution.
Node.js Modules: ECMAScript modules
.mjs, when node.js is loaded, it will automatically use
ESM specification
package.json Add a new configuration item
"type":"module", then all .js files in the entire project will be executed in accordance with the
ESM specifications
--input-type can also achieve the same effect
Various usage methods
1. Conventional method:import _ from 'lodash'; import { readFile } from 'fs'; import Demo from './Demo.mjs'; // 绝对路径或相对路径都可以 export readFile; export default readFile;2. Use with parameters:
// 由于参数不同, 这个会让`foo.mjs`被加载两次,而不会利用缓存中的`foo.mjs` import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1" import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"3. Support
data: format URL form
import 'data:text/javascript,console.log("hello!");'; // text/javascript 会将后面的内容当成js模块 import { test } from 'data:text/javascript,function test(){console.log("test")};export {test};'; // 这里我们是不是扩宽思路,直接加载在线js呢? import _ from 'data:application/json,"world!"' assert { type: 'json' }; // application/json 则是json // application/wasm for Wasm4, assert assertion (experimental feature) Force the file to be loaded into a certain format, such as:
json
javascript
webassembly, etc.
import fooData from './foo.json' assert { type: 'json' };5. Load commonjs specification module
Of course, it also supports loading commonjs standard modules. The usage is as follows:
import { default as cjs } from 'cjs'; // module.exports 导出 import cjsSugar from 'cjs'; // module.exports import * as m from 'cjs';6. import() asynchronous import This kind of usage is very normal. It does not need to be loaded in real time. It will be loaded when it is needed.
const { default: barData } = await import('./bar.json', { assert: { type: 'json' } });7. Supports introduction from http/https (experimental feature)It is currently an experimental feature. Restrictions, such as:
import worker_threads from 'node:worker_threads'; import { configure, resize } from 'https://example.com/imagelib.mjs'; configure({ worker_threads });
Restrictions
The only restriction: when the ESM specification is turned on, you are only allowed to fill inimport or
export, and you are not allowed to use
require or
module.exports, will report an error:
const a = require('a') ^ ReferenceError: require is not defined in ES module scope, you can use import instead at file:///Users/borfyqiu/Desktop/study/github/qiubohong.github.io/code/demo-rollup/test.mjs:4:12 at ModuleJob.run (node:internal/modules/esm/module_job:193:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:530:24) at async loadESM (node:internal/process/esm_loader:91:5) at async handleMainPromise (node:internal/modules/run_main:65:12)
nodejs tutorial!
The above is the detailed content of A brief analysis of how to use import syntax in node. For more information, please follow other related articles on the PHP Chinese website!