How to use Babel Module Resolver

 by Robin Wieruch
 - Edit this Post
babel module resolver, babel module resolver eslint

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.

Keep reading about 

Snapshot tests are a common way to write lightweight component tests. When a snapshot test runs for the first time, it stores its output (e.g. rendered component's HTML structure) in a snapshot output…

I always struggled to use SVG in my React applications. Every time I searched about the topic online, I've found many ways on how to use SVG in React, but once I implemented the approaches, the…

If you found this blog post helpful, please consider supporting what I do.

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.