2

I am trying to lazy load constant file in react. This constant file is not react component just simple javascript files like below :

// constant.js

export const customFunction = () => {
}

// component.js
const {
customFunction,
} = React.lazy(() => import('./constant.js'));

This I am not able to find in browser under developer tools source option. Also due to this getting customFunction undefined error. This code work if do normal import. customFunction using under useEffect()

import {
customFunction
} from './constant.js';
2

1 Answer 1

2

Do not wrap import statement inside React.lazy. Instead only use import() which returns a Promise and it gets resolved to the contents of the mentioned file

Here is a working example

Sign up to request clarification or add additional context in comments.

8 Comments

I tried this but getting error " Couldn't load Custom Script Error: Cannot find module './constant'
What is your react and react-dom version?
"react": "^17.0.1", "react-dom": "^17.0.1"
It is working in the example I mentioned. From your error, it seems that the path provided to the file wasn't correct. Can you share what you tried so far?
I checked path because similar path is working for normal import. I see your example is working.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.