This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

Hello everyone, I am quick-frozen fish 🐟, a front end of water system 💦, like colorful whistle 💐, continuous sand sculpture 🌲, I am a good brother of the next door Cold grass Whale, I just started to write an article. If you like my article, you can follow ➕ to like it, inject energy into me, and grow with me

Read this article 🦀

1. What will you learn about the CommonJS specification

2. What will you learn about the ESM modularity specification

3. How to use the ESM specification in NodeJs

If you are learning how to make CLI tools, I suggest you check out my article 🐬.

“100% Improved development efficiency 🔥” from zero to one you quickly implement enterprise-class CLI tools 🐬

Preface 🌵

We know that before NodeJS, there was no front-end modularity, there was back-end modularity because there were no overly complex development scenarios. After NodeJS was born, it used CommonJS’s modular specification. Since then, JS modularization began to develop rapidly. Modular development can provide code reuse rate and facilitate code management. In general, a file is a module with its own scope that exposes only specific variables and functions. Popular JS modularity specifications include CommonJS and ES6 modularity specifications. 🕶

The text 🦁

What is the CommonJS specification 💚

NodeJS is a major practitioner of the CommonJS specification and has four important environment variables that support modular implementations: Module, exports, require, global. Module. exports defines the interface for the current module’s exports (not recommended), and requires loads the module.

// Define the module math.js
var basicNum = 0;
function add(a, b) {
  return a + b;
}
module.exports = { // Write functions and variables that need to be exposed here
  add: add,
  basicNum: basicNum
}

/** the./ path must be added, otherwise only **/ will be found in node_modules
// When referencing a custom module, the argument contains the path and can omit.js
var math = require('./math');
math.add(2.5);

// No path is required when referencing core modules
var http = require('http'); http.createService(...) .listen(3000);
Copy the code

CommonJS loads modules synchronously. On the server side, the module files are stored on local disk and are very fast to read, so this should not be a problem. However, on the browser side, it is more reasonable to use asynchronous loading for network reasons.

What is the ESM modularity specification 🌽

The ESM modularity specification is also called ES6 modularity specification. It implements module functions on the level of language standard, and it is implemented quite simply, aiming to become a common module solution for browsers and servers. Its module functions are mainly composed of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.

/** Define the module math.js **/
var basicNum = 0;
var add = function (a, b) {
    return a + b;
};
export { basicNum, add };

/** references the module **/
import { basicNum, add } from './math';
function test(ele) {
    ele.textContent = add(99 + basicNum);
}
Copy the code

As shown in the example above, when using the import command, the user needs to know the name of the variable or function to be loaded. In fact, ES6 also provides the export default command, which specifies the default output of the module. The corresponding import statement does not need curly braces.

ES6 modules are not objects, and the import command is statically analyzed by the JavaScript engine. The module code is introduced at compile time, rather than loaded at run time, so conditional loading cannot be implemented. Because of this, static analysis is possible.

Features of ES6 module:

  • Strict mode: ES6 modules automatically adopt strict mode
  • importThe read – only features:importProperty is read-only and cannot be assigned, similar toconstThe characteristics of the
  • export/importPromotion:import/exportMust be at the top level of the module, not in scope; Secondly, for the moduleimport/exportWill ascend to the top of the module, which is done at compile time

Differences between ESM modules and CommonJS modules 🍪

1. The CommonJS module outputs a copy of a value, while the ES6 module outputs a reference to a value. 🐀

  • The CommonJS module outputs a copy of the value, meaning that once a value is output, changes within the module do not affect that value.
  • ES6 modules operate differently from CommonJS. The JS engine encountered a module load command while statically analyzing the scriptimport, a read-only reference is generated. When the script is actually executed, it will be evaluated in the loaded module based on the read-only reference. In other words, ES6importIt’s kind of like a symbolic link on Unix, where the original value changes,importThe loaded value will also change. Therefore, ES6 modules are referenced dynamically and do not cache values. Variables in modules are bound to the module in which they are located.

2. CommonJS module is run time loading, ES6 module is compile time output interface. 🕊

  • Runtime loading: CommonJS modules are objects; That is, the entire module is loaded on input, an object is generated, and methods are read from that object. This loading is called “runtime loading.”
  • Load at compile time: ES6 modules are not objects, but passexportThe command explicitly specifies the code to output,importIs in the form of a static command. In theimportYou can specify that an output value is loaded instead of the entire module, which is called “compile-time loading.”

CommonJS loads an object (that is, the module.exports property) that is generated only after the script runs. An ES6 module is not an object, and its external interface is a static definition that is generated during the code static parsing phase.

How to use ESM in NodeJs 🐳

1. Use the MJS composition file suffix (not recommended) 🍀

hi.msj

// Code of hi.mjs
export function sayHi(name) {
    return "Hi, " + name + "!"
}
Copy the code

main.mjs

// Code of main.mjs
import { sayHi } from './hi.mjs'

console.log(sayHi('Sudongyu'))
Copy the code

shell

node runner.mjs
Copy the code

2. Use the ESM Library (new NodeJs is not recommended) 🐩

This method only applies to older versions of Nodes, which support the ES module out of the box

shell

Install the ESM library

npm init -y
npm install --save esm
Copy the code

The entry file specified in package.json is index.js

// index.js code
require = require("esm") (module);
module.exports = require("./main.js");
Copy the code

3. Configure the module in package.json (recommended) 🐡

package.json

"type": "module"."main": "src/index.js".Copy the code

Specify type as module

Once configured, you can use the ESM modularity specification directly in your project

4. How to use CommonJs specification under ESM specification 🍿

Import createRequire from the Module module (built-in)

import {createRequire} from "module";

const require = createRequire(import.meta.url);

// Get the PackgeJson file information
let pkgManifest = require(path.join(cwd(), 'package.json'));
Copy the code

References 📚

  • NodeJs-esm

  • LogRocket-blog

  • Front-end modular: CommonJS,AMD,CMD,ES6

Harvest 🍁

What do we learn in the passageCommonJs specificationandESM moduleSpecification, and howNodeJsThe use ofESM modularSpecification, so that we can make development moreSimple and quickIn the near future, I believe that modular specifications will be unified, and I hope you have learned something from this article if you are using itNodeJsThe development ofCLI toolTake a look at my article and it may help you

“100% Improved development efficiency 🔥” from zero to one you quickly implement enterprise-class CLI tools 🐬

Conclusion 🌞

So I N article is over, actually very simple, the purpose of the article is the summary of daily work and output, output some feel useful things for people, food is not food is not important, but love 🔥, hope everyone can like my articles, I am really very attentively in writing, also hope that through articles meet more like-minded friends, if you like, Welcome to add my friends, sand sculpture, progress together.

Making 🤖 : sudongyu

Personal blog 👨💻: Frozen fish blog

Vx 👦 : sudongyuer

Write in the last

Guys, if you like my words, give 🐟🐟 a thumbs up 👍 or follow ➕ to support me the most.

Add me on wechat: Sudongyuer, invite you into the group and learning the front together, become a better engineer ~ (group of qr code here – > front to go to bed early, qr code has expired, see the links to the boiling point in the comments, I will put the latest qr code in the comments section, of course, can also add me WeChat I pull you into the group, after all, I also am interesting front end, I also not bad 🌟 ~

“Welcome to the discussion in the comments section. The nuggets will be giving away 100 nuggets in the comments section after the diggnation project. See the event article for details.”