简体   繁体   中英

Create react app + React lazy + Absolute Imports

I have set up jsconfig.json as described in cra documentation. [ https://create-react-app.dev/docs/importing-a-component#absolute-imports][1]

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

It is working fine if write directly to the file.

import Test from 'pages/Test'

But when I try to load it lazy, it is creating problem.

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

Doing this giving error cannot able to find module: pages/Test

But if I write relative path, it is working fine.

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

So, my question is how to import module on dynamically by using absolute path?

Thanks

try to add a "paths" property to "compilerOptions" for pages like this:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
       "pages": "src/pages"
    }
  },
  "include": ["src"]
}

I think you may Suspense missed wrapper component.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM