How do I resolve import with absolute path?

2.1k Views Asked by At

What do I need to setup in brunch-config.js to be able to resolve absolute path from project's root folder? i.e

import { helper } from '/imports/utilities/helper'

The reason being is I have a legacy React app and it imports local files by using relative path. While I'm trying to use brunch, I need to figure out a way to setup brunch so that it understands the path without having to change the code.

I tried to use npm alias but not sure how it works

npm: {
  aliases: {
    '/imports': 'imports/**'
  }
}
1

There are 1 best solutions below

0
spondbob On BEST ANSWER

Found the solution with babel-plugin-module-resolver package.

Since all my codes are under /imports dir, in brunch-config.js I setup an alias based on their documentation:

plugins: {
  babel: {
    plugins: [
      ...,
      ["module-resolver", {
        "root": ["./imports"],
        "alias": {
          "/imports": ([, path]) => `./imports${path}`,
        }
      }]
    ],
    presets: [
      ...
    ],
  }
},

That way, if I do import Screen from '/imports/components/screens' it will resolve the file under ./imports/components/screens

You can set the alias in .babelrc too but you might want to use regex instead.