Skip to content

goodguydaniel.com

Better imports with webpack resolve.alias

Webpack1 min read

I want to write a short article where once more I emphasize one of the superpowers of webpack.

Have you ever came across this in some of your project's codebase(s)?

1import { powerUtility } from "../../../../common/utils";

Wouldn't it be pleasing to refer to a top-level module/namespace in any place you need to import something?

1import { powerUtility } from "@project-x-utils";

With webpack, having something like that, it's very straightforward. Aliasing module names for shorter and clear import statements have considerable gains in terms of codebase discoverability, codebase navigation, and of course, general readability. Aliasing modules is especially helpful for large codebases organized in modules.

Aliasing modules is as simple as using webpack Resolve configurations, more precisely resolve.alias. To follow up on the previous example, here is how your webpack.config.js file should look like if you want to be able to import your utils module as displayed above.

1const webpack = require("webpack");
2// ...
3
4const options = {
5 entry: {
6 // ...
7 },
8 output: {
9 // ...
10 },
11 module: {
12 // ...
13 },
14 resolve: {
15 alias: {
16 // Note: 'src/common/utils' is the path to the module, in this case "utils"
17 "@project-x-utils": path.resolve(__dirname, "src/common/utils"),
18 // ...
19 },
20 },
21 plugins: [
22 // ...
23 ],
24};
25
26module.exports = options;

Now you can go ahead and remove all those 100 characters long relative imports at the beginning of your JavaScript files.