1. 程式人生 > >import() 動態載入語法

import() 動態載入語法

//math.js

console.log("start loading");

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

舊寫法:在編譯時就完成模組載入

import React, { PureComponent } from "react";
import { add } from "./math";

class App extends PureComponent {
  handleClick = () => {
    console.log(add(16, 26));
  };

  render() {
    return <button onClick={this.handleClick}>add</button>;
  }
}
export default App;

新寫法:觸發點選事件後才開始載入模組

import React, { PureComponent } from "react";

class App extends PureComponent {
  handleClick = () => {
    //動態載入
    import("./math").then(math => {
      console.log(math.add(16, 26));
    });
  };

  render() {
    return <button onClick={this.handleClick}>add</button>;
  }
}
export default App;