3

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

Tuhin
  • 3,335
  • 2
  • 16
  • 27
  • CRA uses webpack, and looking at the [webpack module resolution docs](https://webpack.js.org/concepts/module-resolution/#module-paths) I'm guessing the algorithm doesn't work for dynamic imports? – Jared Smith Dec 29 '20 at 11:55

2 Answers2

1

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

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
       "pages": "src/pages"
    }
  },
  "include": ["src"]
}
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
-2

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