Home > Web Front-end > JS Tutorial > body text

A brief analysis of how to use import syntax in node

青灯夜游
Release: 2023-03-21 18:53:22
forward
3782 people have browsed it

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.

A brief analysis of how to use import syntax in node

js modularization

The mainstream front-end modularization specifications currently include the following:

  • CommonJS, the specification proposed by Node.js
  • ECMAScript Module, ESM, the JavaScript standard specification proposed by the ECMAScript organization
  • The ones that have been eliminated are: CMD, AMD, etc., and then the complex UMD ( Supports a collection of various specifications)

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';
Copy after login

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.

How to use

Let’s first read the relevant instructions from the official website:

Node.js has two module specifications: CommonJSModule Specification and ECMAScriptModule Specification Developers can set type=module or node xxx.js --input-type# through the .mjs file extension, package.json The ## flag tells Node.js to use the ECMAScript specification to execute code. Without these settings, Node.js will use CommonJS for execution. Node.js Modules: ECMAScript modules

Through the above we can know several usage methods:

  • Change the file suffix to

    .mjs, when node.js is loaded, it will automatically use ESM specification

  • in the project

    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

  • Adding execution parameters

    --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;
Copy after login

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"
Copy after login

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 Wasm
Copy after login

4, 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' };
Copy after login

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';
Copy after login

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' } });
Copy after login

7. Supports introduction from http/https (experimental feature)

It is currently an experimental feature. Restrictions, such as:

    Does not support http2/3 protocol
  • http protocol can only be used for local IP addresses such as 127.0.0.1
  • Cookie, Authorization and other information are not Will be carried and sent
  • Only the js file of the remote end will be loaded and executed, and other dependent files in the remote end will not be loaded
  • import worker_threads from 'node:worker_threads';
    import { configure, resize } from 'https://example.com/imagelib.mjs';
    configure({ worker_threads });
    Copy after login

Restrictions

The only restriction: when the ESM specification is turned on, you are only allowed to fill in

import 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)
Copy after login

Summary

In fact, this is not a popular knowledge, as long as you have done a little bit of Node.js Keep paying attention and you can basically learn about this feature.

But as someone who doesn’t pay attention, it’s easy to fall into your own misunderstanding of knowledge. You will always think that Node.js does not support the ESM specification, and even complain about why Node.js does not support it?

So here is a sentence that you need to remind yourself - [There is no road in the book mountain, and diligence is the path, and there is no limit to the sea of ​​learning, and the boat is the boat].

For more node-related knowledge, please visit:

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!