首页 > 解决方案 > 动态导入不适用于 Webpack 4 + React + @loadable/component

问题描述

我有一个将 React 与 Webpack 4、Babel 和 TypeScript 一起使用的项目。我正在尝试为此进行代码拆分和安装@loadable/component。不幸的是,当我调用loadable(() => import(...))以将我的一个页面放在不同的块中时,webpack 或 babel 似乎没有意识到这一点,没有任何反应,我只保留一个 JS 文件。搜索文档,SO 的其他问题,但似乎没有任何效果 =\

这是我的.tsx文件:

import loadable from "@loadable/component";

const TextDisplayPage = loadable(() => import("./pages/textDisplayPage"));

const AppRoutes = () => (
  <Switch>
    <Route exact path="/" component={HomePage} />
    <Route
      exact
      path="/introduction"
      render={() => (
        <TextDisplayPage
          textsToDisplay={DisplayTexts.INTRODUCTION}
          continueButtonLinkURL="/character"
        />
      )}
    />
  </Switch>
);

我的.babelrc文件:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": ["@loadable/babel-plugin", "@babel/plugin-syntax-dynamic-import"]
}

我的webpack.config.js文件的一部分(不知道这是否足够的信息,但如果不是让我知道的话):

/*...*/
module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: [/node_modules/],
        use: ["babel-loader", "ts-loader"],
      }
    ]
/*...*/

任何帮助表示赞赏。提前致谢!

标签: reactjswebpackbabeljscode-splittingdynamic-import

解决方案


推荐阅读