webpack alias basics

2020-08-14

 | 

~2 min read

 | 

215 words

Learning about CSS modules recently required digging into Webpack for the first time in a while. One of the pieces that came in handy there was setting aliases for different branches of code to make relative paths easier.

Setting Aliases

Setting aliases is part of the resolve configuration for Webpack. There’s a tremendous amount of variety available, but let’s start with the straight forward case: we have a few directories and we’d like to not have to traverse both directions on the tree.

tree -I \node_modules\*
.
├── index.html
├── package.json
├── src
│   └── components
│   │   ├── alert.js
│   │   ├── index.js
│   │   └── robot.js
│   └── styles
│       ├── app.css
│       └── secondary.css
├── webpack.config.js
└── yarn.lock

Now, we want to create aliases for components and style. (Let’s assume for the moment that we intend to not colocate style sheets with their respective Javascript).

webpack.config.js
module.exports = {
  /*...*/
  resolve: {
    alias: {
      app: path.resolve(__dirname, "src/components"),
      style: path.resolve(__dirname, "src/styles"),
    },
  },
}

Examples

Once this is set up, we can use it in the following ways.

From a Javascript file:

index.js
import greetings from "app/robot";
import styles from "style/app.css";
//...

From a CSS:

app.css
.element {
  composes: center mw40 from "style/secondary.css";
}

Related Posts
  • CSS Modules: An Introduction


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!