timarney / react-app-rewired

Override create-react-app webpack configs without ejecting
MIT License
9.79k stars 425 forks source link

cannot import from outside src if using dynamic variable #509

Closed KS21400 closed 3 years ago

KS21400 commented 3 years ago

import(this.props.imageDetails.url).then(image => { this.setState({ imageUrl : image }); }); here in import if i am using any variable it is showing cannot find module error

but for this it is working import('/opt/intel/eis/data/image-store-bucket/e9ba7f2ca7').then(image => { this.setState({ imageUrl : image },()=> console.log("stateimage",this.state.imageUrl)); });

dawnmist commented 3 years ago

That's actually an issue with dynamic imports in javascript as a whole - you cannot use variables for them. The compiler needs to be able to statically identify what needs to be imported in order to do the build and code splitting, which it cannot do if the import is a variable. This is a basic limitation of the compilers for javascript, and not something related to the use of create-react-app or react-app-rewired.

(Edit: at least, that was my understanding of dynamic imports - I'm seeing some information that seems to be contradicting that, but I'm not sure if that's a difference between babel and node.js as compilers. I'll investigate that part further).

dawnmist commented 3 years ago

Webpack information on dynamic imports starts at: https://webpack.js.org/api/module-methods/#import-1

It basically needs to know at least what directory path to be including, otherwise it does not know what files to include in the compiled bundle for the site. You can work around the issue of variable names to a small degree using template string literals for the last parts of the file path - but you need to be hard-coding at least the first part of the string.