创建 React 应用程序 + React 懒加载 + 绝对路径导入

3

我已按照cra文档中所述设置了jsconfig.json。

[https://create-react-app.dev/docs/importing-a-component#absolute-imports][1]
{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

如果直接写入文件,它能正常工作。

import Test from 'pages/Test'

但是当我尝试进行懒加载时,会出现问题。

const TestPage= React.lazy(() => import('pages/Test'));

这样做会出现错误,无法找到模块:pages/Test。

但是,如果我写相对路径,它就可以正常工作。

const TestPage= React.lazy(() => import('../../pages/Test'));

所以,我的问题是如何使用绝对路径动态导入模块?

谢谢。


CRA使用webpack,查看webpack模块解析文档,我猜算法不适用于动态导入? - Jared Smith
2个回答

1
尝试为页面的"compilerOptions"添加一个"paths"属性,如下所示:
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
       "pages": "src/pages"
    }
  },
  "include": ["src"]
}

-2

我认为你可能错过了包含Suspense的包装组件。

import React, { lazy, Suspense } from 'react';

const TestPage= React.lazy(() => import('pages/Test'));

const renderLoader = () => <p>Loading</p>;

const DetailsComponent = () => (
   <Suspense fallback={renderLoader()}>
      <TestPage />
   </Suspense>
)

https://reactjs.org/docs/code-splitting.html


这与问题有什么关系? - Jared Smith
@JaredSmith 如何使用 Suspense Wrapper 组件的参考文献 - Vigneshwaran Chandrasekaran
不,Suspense包装器组件与模块路径解析有什么关系? - Jared Smith
如果您尝试导入延迟加载组件而不使用Suspense,React将显示错误。为了避免这种情况,请使用Suspense。它会等待动态导入组件加载完成。 - Vigneshwaran Chandrasekaran
我放弃试图向您解释。问题在于模块路径解析失败,与暂停或缺乏暂停无关:OP的代码在使用相对路径时正常工作。这是webpack或CRA的webpack配置的问题。 - Jared Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接