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';

Coming from a PHP background – 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/ui/components/'),
      Containers: path.resolve(__dirname, 'src/ui/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 🙂

Webpack: resolve.alias

Elsewhere , , ,

Leave a Reply

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