Easier imports with Webpack’s resolve.alias

One of the things I find annoying when using import in my JS code is the fact that you need to refer to other local files using (relative) paths. Like so:

// Without resolve.alias 😭

import Modal from '../../../components/objects/modal/modal';

Having a background in PHP – where you have include paths and autoloaders – I essentially want the code to know that all components can be found in src/ui/components, allowing me to freely move files around without needing to update the paths of all import statements.

Turns out Webpack allows one to do exactly just that, using resolve.alias:

const webpackConfig = {
  resolve: {
    alias: {
      Components: path.resolve(__dirname, 'src/components/'),
      Containers: path.resolve(__dirname, 'src/containers/')

With resolve.alias in place, imports can now be written as such, regardless of the location of the file importing it:

// With resolve.alias 😊

import Modal from 'Components/objects/modal/modal';

Aaah, much better 🙂

To not have to alias all folders, I’ve seen some people alias src/ to @. That way they can import from @/Components/…. Clever.

Webpack: resolve.alias

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.