DEV Community

Cover image for Simplify your imports with webpack aliases 👍
George Francis
George Francis

Posted on

Simplify your imports with webpack aliases 👍

I get confused with relative import paths literally all the time. It's annoying and can really take you out of the "zone" when solving a problem. Luckily this morning I stumbled across a great solution, it's fairly simple and can be implemented in a webpack setup with just a few extra lines.

By adding some options to webpack's resolve configuration object, we can define aliases for specific directories. For example:

We could define the alias Components so that instead of having to do stuff like this:

import MyComponent from '../../../../components/MyComponent.js'
Enter fullscreen mode Exit fullscreen mode

We could do just do:

import MyComponent from 'Components/MyComponent.js'
Enter fullscreen mode Exit fullscreen mode

Quite nice eh? I definitely think so!

Implementation

Head over to your webpack config file and add the following:

const path = require('path');

module.exports = {
  // configuration options for how webpack resolves modules
  resolve: {
    alias: {
      // add as many aliases as you like! 
      Components: path.resolve(__dirname, 'path/to/your/components/dir') 
    }
  }
  // ... rest of your config
}
Enter fullscreen mode Exit fullscreen mode

Once you have added whatever aliases you need to the resolve object you should be good to go 🔥

Note: you can find the official webpack docs for resolve here: https://webpack.js.org/configuration/resolve/

Hopefully some folks find this useful and thanks for reading!

Top comments (1)

Collapse
 
abhaysonideveloper profile image
Abhay Soni

i have created jsconfig with paths in it , i want webpack resolve to take those paths into consideration and automatically built alias , if there is already a plugin available please name it, i do not want to reinvent the wheel,