I was experiencing a similar problem. I finally resolved it by following this article: https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

  1. Create a .env file in the root of the react app
  2. Add a line NODE_PATH = src/

That worked for me.

Answer from DigiBanks99 on Stack Overflow
๐ŸŒ
Medium
sohamnakhare.medium.com โ€บ import-react-component-using-a-variable-path-94d2f1492d40
Import react component using a variable path | by Soham Nakhare | Medium
December 13, 2023 - Simply specify the directory to be scanned, and that should resolve it. ... Webpack configuration can be intricate and may appear mystifying at times, but it is a highly potent tool equipped with numerous features.
Discussions

Dynamic import with variable path
There is almost certainly a better solution, this isnt a very good approach in programming in general. Its highly untestable, brittle, and results in code that isn't easily minified or optimally bundled. As to what that better solution looks like, there's no way to suggest anything without an explanation of the type of problem you're trying to solve. What problem exists that you're trying to solve with this? More on reddit.com
๐ŸŒ r/reactjs
13
17
November 25, 2021
reactjs - How to import a component or file in React using variables? - Stack Overflow
I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus. I have a "Content" component that loads the campus or building map, dependin... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Reactjs: How to import an image from a variable path
What first coming to my head is to create stateless component which will take your flag object and show tag with specific path. It won't import as react suggest but it will do the job :) Instead if u really want use react approches you could use require instead of import, checkout below question, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
reactjs - React - inserting variable into Route path - Stack Overflow
I have an app that I am creating and am wondering how you would insert variables into the I am trying to create a myProfile page and... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 2
12

Thereโ€™s limitation when using dynamic imports with variable parts.

Webpack Docs

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included.For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

In your case, during build time for dynamic import in FirstComponent component, bundling was limited to directory where the FirstComponent component was i.e. Components directory.

What it means is that, webpack will find all the files that are in the Components directory and then create chunks for them. Then at runtime when dynamic import is called, webpack will serve the chunk that corresponds to the value passed in.

Since you passed path= '../FooterComp/Footer' has no corresponding chunk so webpack will throw the error.

This is also same for Dynamic component. If you try to dynamically import with variable parts for the files that are outside src folder, you will get same error.

So to solve this you have couple of options

  1. place both files in same folder

i.e

'src/Components/FirstComponent.js'

'src/Components/Footer.js'

And use

// In FirstComponent.js
   componentDidMount() {
      const { path } = this.props;
      import(`${path}`)
      .then(module => this.setState({ module: module.default }))   
   }


{Component && <Component path='./Footer' />} // Index.js
  1. be more specific as possible

i.e

// In FirstComponent.js
 componentDidMount() {
      const { path } = this.props;
      import(`../FooterComp/${path}`)
      .then(module => this.setState({ module: module.default }))   
 }

And use

{Component && <Component path='Footer' />} //  In index.js
2 of 2
0

If FooterComp is under src, the path should be './FooterComp/Footer' not '../FooterComp/Footer'


Edit

Index.js

    render() {
          console.log('in render')
         // alert("in render")
        const { module: Component } = this.state; 
        return(
          <div>
            {Component && <Component path='./Components/FirstComponent' />}
          </div>
        )
      }
    }

ReactDOM.render(<Dynamic />, document.getElementById('root'));

FirstComponent.js

render() {
      const { module: Component } = this.state;
    return (
      <div className="App">
        <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
        {Component && <Component path= '../FooterComp/Footer' />}
      </div>
    );
  }
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ dynamic import with variable path
r/reactjs on Reddit: Dynamic import with variable path
November 25, 2021 -

I'm looking for a way to dynamically import a component from a path including a variable, and display a fallback component. Currently I'm doing this with an intermediary component:

const DynamicComponent = ({ element, elementName }) => {
    
    const [component, setComponent] = useState(element)

    useEffect(() => {
        import(`/components/${element.type.name}`)
            .then(module => {
                setComponent(module.default)
            })
            .catch(console.log)
        }, [element])

    return component
}

Which is then used like this:

<DynamicComponent element={<SomeComponent />} elementName="SomeComponent" />

The elementName prop is required because in production the function names are minified so I can't get the component name from anywhere else.

This seems to work well locally, but is pretty flaky in production - it errors far more often, and sometimes doesn't show the right component which appears to be related to how and when the dynamic path is generated.

Can anyone recommend a cleaner/better/simpler solution?

Thanks!

Top answer
1 of 3
5

You could have a file import all the images like

//images/index.js

import image1 from './image1.png'
import image2 from './image2.png'
.
.
export default {
image1,
image2,
.
.
}

you can access images dynamically from the object exported from here

import images from './images/index.js'
images['image1'] 

// or dynamically
let name = 'image2'
images[name]
2 of 3
3

You can try with:

Using import for browser and nodejs

const picture = (await import(`../path/to/file/${this.props.picPath}`)); // this is async

Using require for browser and nodejs

const picture = require(`../path/to/file/${this.props.picPath}`); // this is sync

Using readFileSync from fs only for nodejs

const fs = require('fs')
// or: import fs from 'fs'

const file = fs.readFileSync(`../path/to/file/${this.props.picPath}`).toString()

Using readFile from fs only for nodejs

const fs = require('fs')
// or: import fs from 'fs'
const file = (await fs.readFile(`../path/to/file/${this.props.picPath}`)).toString()

Tip #1:

When you using require, it only can handle json and js files, but when you using import, it can handle svg, and other stuff. But you can apply some trick like:

// in tsconfig.json
"include": [
    "./declarations.d.ts",
],
// in declaration.d.ts
declare module '*.png';

Tip #2:

When you wanna import images like png, you should be define how it work with this:

declare module "*.png" {
  const value: any;
  export default value;
}

Tip #3 In javascript you can use Template Literals using `` and ${}.

const name = "John"
console.log(`Hello ${name}`);

Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71362482 โ€บ variable-path-import-in-react-js
reactjs - Variable path import in react JS - Stack Overflow
I'm new to react and these days I'm doing a project in react JS. So, I needed to make a function like in the below code. So, I needed to import like this. But it's returning a promise instead. So ...
๐ŸŒ
DEV Community
dev.to โ€บ smitterhane โ€บ avoid-relative-path-import-hell-in-react-36in
Avoid relative path import hell in react - DEV Community
September 10, 2022 - You can use absolute paths to solve these issues. You need to configure your application to support importing modules using absolute paths. This can be done by configuring a jsconfig.json or tsconfig.json file in the root of your project.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 77811240 โ€บ how-to-get-module-import-path-of-a-react-component
How to get module import path of a react component?
January 13, 2024 - T.J. Crowder โ€“ T.J. Crowder ยท 2024-01-13 14:13:40 +00:00 Commented Jan 13, 2024 at 14:13 ... If you mean in code at runtime, you can't. The module specifier (path) isn't stored anywhere on components exported from modules.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ how to get module import path of a react component?
r/reactjs on Reddit: How to get module import path of a react component?
January 13, 2024 - the path is passed to a global window variable and then used in a hydration script via a dynamic import ยท i can just have my response method use strings instead of the actual react jsx component, but i thought it would be awesome if i could do it that way More replies
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ relative import paths and aliases when using create react app
r/reactjs on Reddit: Relative Import Paths and Aliases When Using Create React App
June 12, 2022 -

What's the general consensus on relative import paths? Are people using relative paths to import their components or are you using a different approach? I've detailed the solutions to relative import paths that I'm aware of and why I don't like any of these approaches.

For clarity, below is an example of what I'm referencing

import MyComponent from "../../../components/MyComponent"

Update that to this

import MyComponent from "@components/MyComponent"

Potential solutions and their drawbacks:

  • Relative Import Paths - these are just annoying, there should be a cleaner solution

  • Craco - doesn't work with react-scripts 5.0

  • Utilizing Absolute Import Paths: doesn't directly solve the problem (still need to list all folders below the "src" folder)

  • Webpack from Scratch: Don't use CRA and create webpack config files from scratch: this is a lot of work for simply having aliased imports

Cheers!

๐ŸŒ
DeKu
deku.posstree.com โ€บ home โ€บ react โ€บ make import path based on root in react
Make Import path based on Root in React | DeKu
June 12, 2019 - |-- src | |-- index.html | |-- App.tsx |-- .babelrc |-- package.json |-- webpack.config.js ยท execute the command below to install babel-plugin-root-import to make import path based on Root.
๐ŸŒ
Create React App
create-react-app.dev โ€บ docs โ€บ importing-a-component
Importing a Component | Create React App
April 11, 2021 - Thatโ€™s what you get when you use export default Button and import Button from './Button'.
๐ŸŒ
LinkedIn
linkedin.com โ€บ posts โ€บ yogesh-chavan97_react-tip-avoid-writing-relative-paths-activity-7042347643959685120-bqpu
Yogesh Chavan on LinkedIn: ๐Ÿ’ก React Tip๐Ÿ’ก Avoid writing relative paths while importing files in yourโ€ฆ
March 17, 2023 - Follow the below steps: โœ… Install ... to be added โœ… Press Ctrl+Shift+H or Cmd+Shift+H (Mac) to open the search bar โœ… Then type the name of the file you want to import from and โœ… press the enter key and the complete file ...