← Back toFront-end tips

Shorten import paths in Webpack

Written byPhuoc Nguyen
Created
17 Mar, 2021
Category
Tip
Tags
Webpack
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:
js
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:
js
// 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:
js
import { formatDate } from '@/helpers/formatDate';
Webpack will be looking for the helper in the `src/helpers/formatDate` file.

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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