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 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).
module.exports = {
/*...*/
resolve: {
alias: {
app: path.resolve(__dirname, "src/components"),
style: path.resolve(__dirname, "src/styles"),
},
},
}
Once this is set up, we can use it in the following ways.
From a Javascript file:
import greetings from "app/robot";
import styles from "style/app.css";
//...
From a CSS:
.element {
composes: center mw40 from "style/secondary.css";
}
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!