How to use Babel Module Resolver

 by Robin Wieruch
 - Edit this Post

The following implementation is a quick excerpt from one of my daily tasks as a software developer. If I run into a problem and arrive at an example that I find worth sharing, I will put a gist of the code up on this website. It might be useful for someone else stumbling across the same task.

In this brief walkthrough, we will use Babel Module Resolver to convert relative paths to aliases for your entire JavaScript application. You can install it via the command line:

npm install babel-plugin-module-resolver --save-dev

And use it in your .babelrc file to create your first module alias:

{
...
"plugins": [
[
"module-resolver",
{
"alias": {
"@icons": "./src/components/icons"
}
}
]
],
...
}

In this case, we are giving all our Icons an alias path. Imagine you would have another src/services/icon.js file which deals with your icons. Now it has an easier time to import an icon from the src/icons folder:

// old way to import
import { CheckIcon } from '../components/icons'
import CancelIcon from '../components/icons/CancelIcon'
// new way to import
import { CheckIcon } from '@icons'
import CancelIcon from '@icons/CancelIcon'

In your .babelrc file, you can introduce more of these aliases to tidy up your imports for your entire JavaScript application.

Babel Module Resolver with ESLint

If you are using ESLint, you have to let ESLint know about the aliases defined in Babel's Module Resolver. First, install two more packages:

npm install eslint-plugin-import eslint-import-resolver-babel-module --save-dev

And second, in your .eslintrc use these new plugins to match Babel's Module Resolver with ESLint:

{
...
"extends": [
"plugin:import/errors",
"plugin:import/warnings"
],
"settings": {
"import/resolver": {
"babel-module": {}
}
},
...
}

That's it. ESLint should be happy about Babel's Module Resolver now.


Babel Module Resolver helps you to tidy up your relative imports for your entire JavaScript application. If you want to avoid moving up and down folders with relative paths, add aliases to crucial paths of your application to make it easier to import modules from these areas.

This tutorial is part 1 of 2 in the series.

This tutorial is part 1 of 2 in the series.

Keep reading about 

Here you will learn how to use Jest with Babel Module Resolver for aliases that are defined in your .babelrc file: In order to get the same alias mappings to Jest, the jest.config.js file needs to…

Here you will learn how to use TypeScript with Babel Module Resolver for aliases that are defined in your .babelrc file: In order to get the same alias mappings to TypeScript, the tsconfig.json file…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.