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.
More
