← Back toFront-end Tips

Shorten import paths in Webpack

Written byPhuoc Nguyen
Category
Tip
Tags
Webpack
Created
17 Mar, 2021
Say you're using Webpack to bundle your application. If you think that using a relative path when importing a given file is ugly and hard to maintain when changing the directory structure:
import { formatDate } from '../../../helpers/formatDate';
Then using the aliases is one of the solutions. Webpack allows to map a prefix of import path to a given path. For example, we would like to map all the imports starting with `@` to the `src` folder.
The Webpack config looks like:
// webpack.config.js
const path = require('path');

module.exports = {
resolve: {
alias: {
// Assume that the `src` folder is located at the root folder
'@': path.join(__dirname, 'src'),
},
},
};
The helper function mentioned at the top can be shorten as below:
import { formatDate } from '@/helpers/formatDate';
Webpack will be looking for the helper in the `src/helpers/formatDate` file.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn