Skip to the content.

webpack and react 按需加载

react-router 中使用按需加载

使用 react.lazy

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import React, { Suspense, lazy } from "react";

const Program1 = lazy(() => import("./Program1"));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route path="/program1" component={Program1} />
      </Switch>
    </Suspense>
  </Router>
);

配置 webpack 4+版本

...
  output: {
    path: path.resolve(root, 'dist/dev'),
    publicPath: '/',
    filename: 'index.[hash:10].js',
    chunkFilename: '[name].[chunkhash:10].chunk.js',
  },
...

查看代码

参见