webpack

weback利用动态 import 代码分割

2020-12-05  本文已影响0人  阿畅_

代码分割的意义

懒加载 JS 脚本的方式

使用动态import

npm i @babel/plugin-syntax-dynamic-import -D
{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}
// 声明一个组件
<Text/>

class Index extends React.Component {
  constructor() {
    this.state = {
      Text: null
    }
  }
  // 点击才会加载Test组件
  onLoadComponent() {
    import('./Test.js').then((Text) => {
      this.setState({
        Text: Text.default
      })
    })
  }
  render() {
    const { Text } = this.state
    return <div onClick="onLoadComponent">
      <span>react</span>
      { Text && <Text/> }
    </div>
  }
}

在 webpack 中是通过 JSONP 的方式将 Test 脚本加载进来

上一篇 下一篇

猜你喜欢

热点阅读