2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Each js file is a module, and the CommonJS module specification is adopted by default.
Emerging ES6 modules vs. traditional CommonJS modules
characteristic | CommonJS | ES6 Modules |
---|---|---|
Export | exports Object | export Keywords |
Import | require() function | import Keywords |
Loading Mode | Synchronize | asynchronous |
Execution Mode | Singleton | Singleton |
Dependencies | Static | dynamic |
Tree Shake | not support | support |
Loading Mode
Execution Mode
Both CommonJS and ES6 module implementations are singletons: a module is loaded only once, and all references to the module refer to the same instance.
Dependencies
Tree Shake
An optimization technique for removing unused code from JavaScript bundles.
Three ways to enable ES6 modules
"type": "module"
, so that Node.js will treat all .js files as ES6 modules..mjs
, so that Node.js will automatically treat it as an ES6 module.type="module"
AttributesES6 module syntax
Each module can only have one default export.
let a = 1
// 默认导出 a
export default a
// 导入默认时,可以命其他名称
import b from './demo.js'
console.log(b)
You can use function expressions/anonymous functions directly as default exports
export default function myFunc() {}
export default function() {}。
let a = 1
let b = 2
export { a, b }
// 导入多项时,必须与导出名对应
import { a, b } from './demo.js'
console.log(a, b)
let a = 1
let b = 2
export { a as c, b as d }
// 导入时,只能导入新的名称
import { c, d } from './demo.js'
console.log(c, d)
export { name1, name2, ... } from 'module-name'
export let a = 1;
export let b = 2;
// 通过 as 重命名为一个变量(值为对象)
import * as myModule from "./demo.mjs";
console.log(myModule.a);
console.log(myModule.b);
import {trunc as StringLib} from "../lib/string.js"
import {trunc as MathLib} from "../lib/math.js"
import pkg from "./package.json" assert { type: "json" };
const { default: jsonObject } = await import('./file.json', {
assert: {
type: 'json'
}
});
import * as 自定义名称 from '模块名称'
CommonJS module syntax
Export
module.exports = "朝阳";
Import
const demoModule = require("./demo.js");
console.log(demoModule); // 朝阳
Export
exports.a = 1;
exports.b = 2;
Import
const demoModule = require("./demo.js");
console.log(demoModule); // { a: 1, b: 2 }