JavaScript ES Module的使用

首先,如果要使用ES Module,你需要这样写

1
<script type="module" src="./js/main.js"></script>

或者这样:

1
2
3
<script type="module">
import print1 from "./js/module.js";
</script>

记住一定要写type="module",还有路径一定要是相对路径。

import 的几种用法:

1
2
3
4
5
6
7
8
9
10
11
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
var promise = import("module-name");

export的几种用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var
export let name1 = …, name2 = …, …, nameN; // also var, const
export function FunctionName() {...}
export class ClassName {...}

export default expression;
export default function () { … } // also class, function*
export default function name1() { … } // also class, function*
export { name1 as default, … };

export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;

举一个例子:

index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="module">
import defaultFun from "./js/module.js";
import {test1} from "./js/module.js";
defaultFun();
test1();
console.log("end");

</script>
</body>
</html>

module.js:

1
2
3
4
5
6
7
8
9
export default function () {
console.log("defaultFunction");
}


export function test1() {
console.log("test1");
}

再举一个例子:

index.html:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="module" src="./js/main.js"></script>
</head>
<body>
</body>
</html>

main.js:

1
2
import defaultFun2 from "./module2.js";
defaultFun2();

module2.js:

1
2
3
export default function () {
console.log("print2");
}