// module.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
// main.js
import { add, PI } from './math.js';
// import * as mat from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14
// console.log(mat.add(2, 3)); // 5
// console.log(mat.PI); // 3.14
// module.js
export default const PI = 3.14;
// main.js
import anyName from './math.js';
if (someCondition) {
const module = await import('./module.js');
module.doSomething();
}
defer
BehaviorWhen using <script type="module">
, it behaves as if it has the defer
attribute by default:
If multiple <script type="module" src="...">
are present, they execute in order of appearance in the HTML, just like defer
scripts.
Example:
<script type="module" src="a.js"></script>
<script type="module" src="b.js"></script>
a.js
executes first, followed by b.js
, even if b.js
loads faster.When using import
within a module script: