Avoiding relative imports in a React app

Even with a moderately large React app, you try to structure your modules and end up here in the end:

import ../../../components/dialogs/enter.jsx


Good luck refactoring that! or moving a few components around.

Unfortunately, React evolves, and things that woroked before doesnt anymore.

Previously, you could define en environment variable (either in the shell or in an .env file)


Now however, you have to use a jsconfig.json file, and specify the baseUrl.

You don’t get a default jsconfig.json with Create React App, so you will have to create it from scratch.

    "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "baseUrl": "./src"

Now you can do

import components/dialogs/enter.jsx

I don’t think you can specify multiple places though.

Also, when investigating this, I saw many mentions of how to use webpack and/or babel to resolve module. I have no idea how to do that, I stick with the above that works now, in March 2020.

Also, there are som other keywords in jsconfig.json that are either used by VS Code, or not supported at all. As per usual in the wild JS environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.