search
HomeWeb Front-endJS TutorialA brief analysis of how to use import syntax in node

A brief analysis of how to use import syntax in node

Mar 21, 2023 pm 06:53 PM
nodejs​nodeimport

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';

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;

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 Wasm

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' };

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:

    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 });

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)

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function