0%

References between js

If module is referenced by index.html, all js below that module can use the function without referenced module, even needn’t import and module.js needn’t export.

If module.js doesn’t be referenced by index.html, other js can only import module.js function and which also need to export.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script src="./moduleC.js"></script>
<script src="./main.js" type="module"></script>
</html>
1
2
3
4
5
6
7
8
// main.js
console.log('main1')
import {a} from './moduleA.js'
import {moduleB} from './moduleB.js'
a()
moduleB()
moduleC()
console.log('main2')
1
2
3
4
5
6
7
// moduleA.js
import { moduleB } from './moduleB.js'
export var a = function(){
moduleB()
moduleC()
}
console.log('aaa')
1
2
3
4
5
// moduleB.js
export let moduleB = function(){
console.log('moduleB');
}
console.log('bbb')
1
2
3
4
5
// moduleC.js
function moduleC() {
console.log('moduleC');
}
console.log('ccc')
1
2
3
4
5
6
7
8
// output
ccc
bbb
aaa
moduleB
moduleC
moduleB
moduleC

Because moduleC.js is upper than main.js, so ccc first. And I guess all code should waiting the module loaded then run. First, import moduleA in faster than moduleB in main.js, and moduleB is referenced by moduleA. So it will output bbb first, then aaa. And moduleB.js has been referenced, so it wouldn’t occur again even main.js refer it.

請打賞支待一下.