Adding Path Aliases In Webpack Projects

JavaScript

28/06/2021


I generally prefer to use absolute paths over relative paths as the latter can be a nightmare 😱 to use at times. And Webpack offers a straightforward way to implement this with path aliases.

JAVASCRIPT
import { function } from '../../some/file' // From this,
import { function } from '~some/file' // To that!

Path prefixes

I haven't seen much discussion about whether you should prefix a symbol to a path or even which symbol it should be, for that matter (e.g. ~ or @). So let me briefly give my 2 ✌️ cents on this matter.

I prefer prefixing my paths with ~, aka a tilde. Why? Well, I want to make it clear that the module I'm importing is from the project itself. An @ gives me the impression I'm importing an external npm/Yarn package. Adding no prefix at all conveys the same thing.

What's left? The tilde isn't associated with anything in the JavaScript ecosystem. Fun fact, it's actually used in Unix/Linux to represent your home directory! 😆

Configuration

Enough talk. In your webpack configuration file, look out for the resolve property. In it, you can add as many aliases as you desire.

JAVASCRIPT
module.exports = {
resolve: {
// Add aliases here
alias: {
'~components': path.resolve(__dirname, 'src/components/'),
pages: path.resolve(__dirname, 'src/pages/'),
utils: path.resolve(__dirname, 'src/utils.js'),
}
}
}

The alias property takes an object, where

  • The key represents the path alias, and
  • The value the absolute system path to the folder or file.

Fortunately, __dirname returns the root directory of the project. Therefore, you only need to know the remaining path to your desired folder or file.

If you want to prefix a symbol to a path alias, make sure to wrap it in quotes.


WRITTEN BY

Code and stuff