DEV Community

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

Posted on

11 1

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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,

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay