JavaScript 模块化

本文最后更新于:2024年3月18日 凌晨

JavaScript 模块化

Common JS

  • CommonJS使用 exports 和require 来导出,导入模块。

导出

  • moduleA.js
1
2
3
4
5
6
module.exports = {
flag = true,
add(a, b) = {
return a+b;
}
}

导入

1
2
3
4
5
6
7
//CommonJS 模块。
let { flag, add } = require.('moduleA');

// 等同于。
let _mA = require('moduleA');
let add=_mA.add;
let flag=_mA.flag;

ES6

  • ES6使用export和import来导出,导入模块。

导出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 导出单个特性。
export let name1, name2,…, nameN; // also var, const
export let name1 =…, name2 =…,…, nameN; // also var, const
export function FunctionName(){...}
export class ClassName {...}

// 导出列表。
export { name1, name2,…, nameN };

// 重命名导出。
export { variable1 as name1, variable2 as name2,…, nameN };

// 解构导出并重命名。
export const { name1, name2: bar } = o;

// 默认导出。
export default expression;
export default function () {…} // also class, function*
export default function name1() {…} // also class, function*
export { name1 as default,…};

// 导出模块合集。
export * from…; // does not set the default export
export * as name1 from…; // Draft ECMAScript® 2O21
export { name1, name2,…, nameN } from…;
export { import1 as name1, import2 as name2,…, nameN } from…;
export { default } from…;
  • nameN:要导出的标识符(以便其他脚本通过import语句进行导入)

导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 默认导入。
import defaultExport from "module-name";
// 导入模块合集。
import * as name from "module-name";
import defaultExport, * as name from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
// 导入列表。
import { export } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
// 重命名导入。
import { export as alias } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
// 直接导入。
import "module-name";
  • defaultExport:导入模块的默认导出接口的引用名。
  • module-name:要导入的模块,通常是包含目标模块的.js文件的相对或绝对路径名,可以不包括.js扩展名,某些特定的打包工具可能允许或需要使用扩展或依赖文件,它会检查比对你的运行环境,只允许单引号和双引号的字符串。
  • name:导入模块对象整体的别名,在引用导入模块时,它将作为一个命名空间来使用。
  • export, exportN:被导入模块的导出接口的名称。
  • alias, aliasN:将引用指定的导入的名称。

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!