Skip to content

ES Module 在浏览器中的应用

分类讲解

基本使用

文件 /src/math.js

js
export function add(a, b) {
  return a + b;
}

export function multi(a, b) {
  return a * b;
}

测试文件 test1.html

html
<p>基本演示</p>

<script type="module">
  import { add, multi } from './src/math.js';

  console.log('res add', add(2, 3)); // res add 5
  console.log('res multi', multi(2, 3)); // res multi 6
</script>

外链引入

文件 /src/index.js

js
import { add, multi } from './math.js';

console.log('res add', add(2, 3)); // res add 5
console.log('res multi', multi(2, 3)); // res multi 6

测试文件 test2.html

html
<p>外链</p>

<script type="module" src="./src/index.js"></script>

远程引入

测试文件 test3.html

html
<p>远程引用</p>

<script type="module">
  import { createStore } from 'https://unpkg.com/[email protected]/es/redux.mjs';

  console.log('createStore', createStore);
  // createStore ƒ i(n,f,u){var c;if("function"==typeof f&&"function"==typeof u||"function"==typeof u&&"function"==typeof arguments[3])throw Error(r(0));if("function"==typeof f&&void 0===u&&(u=f,f=void 0),void 0!==u){i…
</script>

按需动态引入

测试文件 test4.html

html
<p>动态引入</p>
<button id="btn1">load1</button>
<button id="btn2">load2</button>

<script type="module">
  btn1.addEventListener('click', async () => {
    const add = await import('./src/add.js');
    console.log(add);
    // Module {Symbol(Symbol.toStringTag): 'Module'}
    // default: ƒ add(a, b)
    //   Symbol(Symbol.toStringTag): "Module"
    //   get default: ƒ ()
    //   set default: ƒ ()
    const res = add.default(1, 2);
    console.log('res add', res);
    // print add
    // res add 3
  });
  btn2.addEventListener('click', async () => {
    const { add } = await import('./src/math.js');
    console.log(add);
    // ƒ add(a, b) {
    //   return a + b
    // }
    const res = add(1, 2);
    console.log('res add', res); // res add 3
  });
</script>

基于 MIT 许可发布