loading...
Cover image for Simplify your imports with webpack aliases 👍

Simplify your imports with webpack aliases 👍

georgedoescode profile image George Francis ・1 min read

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'

We could do just do:

import MyComponent from 'Components/MyComponent.js'

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
}

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!

Discussion

markdown guide