使用React.lazy,Suspense和react-router-dom进行代码拆分不起作用

时间:2019-09-11 11:07:36

标签: reactjs typescript webpack react-router-dom code-splitting

我正在尝试建立一个非常基本的示例,类似于:https://reactjs.org/docs/code-splitting.html#route-based-code-splitting

它应该根据当前路由动态地延迟加载路由组件(ModuleOne或ModuleTwo)及其相关性。

但是看起来代码拆分无法正常工作,并且所有内容都包含在一个捆绑包中。

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index',
  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[name].bundle.js',
    path: path.resolve(__dirname, '../dist'),
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        exclude: /node_modules/,
      }
    ],
  },
  resolve: {
    modules: ['node_modules', path.resolve(__dirname, '../src')],
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  }
};

App.tsx

import * as React from 'react';
import { HashRouter as Router, Link, Route, Switch } from 'react-router-dom';
import * as styles from './App.scss';

const LazyModuleOne = React.lazy(() => import('../modules/ModuleOne/ModuleOne'));
const LazyModuleTwo = React.lazy(() => import('../modules/ModuleTwo/ModuleTwo'));

const App = () => (
    <Router>
        <div className={styles.wrapper}>
            <nav>
                <Link to="/">Start</Link>
                <Link to="/module-one">Module One</Link>
                <Link to="/module-two">Module Two</Link>
            </nav>
            <main>
                <React.Suspense fallback={<div>Loading...</div>}>
                    <Switch>
                        <Route path="/module-one" component={LazyModuleOne} />
                        <Route path="/module-two" component={LazyModuleTwo} />
                    </Switch>
                </React.Suspense>
            </main>
        </div>
    </Router>
);

export default App;

ModuleOne.tsx

import * as React from 'react';
import * as _ from 'lodash';
import { RouteComponentProps } from 'react-router';

const apples = _.fill([1,2,3], 'apple');

const ModuleOne: React.FC<RouteComponentProps> = () => (
  <div>
    <div>ModuleOne</div>
    <div>There are {apples.length} apples</div>
  </div>
)

export default ModuleOne;

ModuleTwo.tsx

import * as React from 'react';
import * as R from 'ramda';
import { RouteComponentProps } from 'react-router';

const cherries = [1,2,3];

const ModuleTwo: React.SFC<RouteComponentProps> = () => (
  <div>
    <div>ModuleTwo</div>
    <div>There are {R.length(cherries)} cherries</div>
  </div>
)

export default ModuleTwo;

演示: enter image description here

有人知道为什么基于路由的代码拆分无法按预期进行吗?

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。与TypeScript相关。我需要设置:

{
  "compilerOptions": {
    "module": "esnext",
  },
}

代替commonjs

现在,代码拆分工作正常。

答案 1 :(得分:0)

我的React版本是16.4.0,可以使用它!

我和你之间的唯一区别:

i使用BrowserRouter。 您使用了HashRouter。