Amit Dhamu

Software Engineer

Aliased Imports in Webpack

When writing modern JavaScript applications, it is easy to end up with lots of import statements. This can easily get quite messy.

import React from 'react';
import * as PropTypes from 'prop-types';
import {graphql, useStaticQuery} from 'gatsby';
import Header from '../layout/Header';
import {helperFunction} from '../../helpers/';
import Widget from '../../modules/widgets/Widget';
import '../../styles/main.scss';

As the above shows, the relative imports can begin to look quite difficult to maintain. Refactoring would also present a problem if we wanted to move the above code to a different file as we'd have to update the paths accordingly.

Luckily, we can use aliased imports in Webpack to help us with this.

const webpack = require('webpack');
const path = require('path');

module.exports = {
    resolve: {
        extensions: ['.jsx', '.js', '.scss'],
        alias: {
            '@styles': path.resolve(__dirname, 'src/scss/'),
            '@modules': path.resolve(__dirname, 'src/modules/'),
            '@helpers': path.resolve(__dirname, 'src/helpers/'),
            '@layout': path.resolve(__dirname, 'src/components/layout/'),
        }
    },
}

The above config tells Webpack to resolve all .jsx, .js and .scss file extensions and map a list of aliases to their respective real paths. I have used an @ symbol for the aliases but you don't have to.

Rewriting our code from above can now look like this:

import React from 'react';
import * as PropTypes from 'prop-types';
import {graphql, useStaticQuery} from 'gatsby';

import Header from '@layout/Header';
import {helperFunction} from '@helpers';
import Widget from '@modules/widgets/Widget';

import '@styles/main.scss';

This now makes the statements alot more cleaner. It also means that if we were to move this file somewhere else, the imports would still resolve as they're mapped to absolute paths.

Bonus

If you're using Gatsby, you can accomplish the same thing with a plugin and updating gatsby-config.js.

yarn add gatsby-plugin-alias-imports
module.exports = {
    plugins: [
        {
            resolve: `gatsby-plugin-alias-imports`,
            options: {
                extensions: ['jsx', 'js', 'scss'],
                alias: {
                    '@styles': 'src/scss/',
                    '@modules': 'src/modules/',
                    '@helpers': 'src/helpers/',
                    '@layout': 'src/components/layout/',
                },
            }
        },
    ],
}

 webpack / alias / import / gatsby

Some New PHP 7 FeaturesImplementing Dark Mode

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.