to navigateEnterto select Escto close

    Create alias for commonly used directories

    What is webpack alias?

    Define aliases for specific directories in order to simplify import statements.

    Why webpack alias?

    Initially, when you start off a project, you don’t mind writing long relative paths and ignore all the troubles that come with it. But as your project starts to scale past a certain point of complexity, you’ll find traversing up and down your file system is time-consuming and error-prone.

    If you are changing the directory structure of a module in your project. This will break all the module references and you will be forced to change all occurrences of the module throughout your project. It will be a daunting task!

    More on aliasing

    Creating alias

    Webpack allows you to create aliases to import or require certain modules through the resolve.alias property in your config without any additional plugins.

    Changes to webpack config

    1  resolve: {
    2    alias: {
    3      apis: path.resolve(__dirname,"apis" ),
    4      components: path.resolve(__dirname,"components" ),
    5      common: path.resolve(__dirname,"components/Common" ),
    6      images: path.resolve(__dirname, "..", "..", "app/assets/images"),
    7      constants: path.resolve(__dirname,"components/constants" ),
    8    },
    9  },

    Webpack resolve

    Updating import statements

    Instead of this:

    1import { createUser } from "../../../apis/user";
    2import { Header } from "../../common";

    It should be written like this:

    1import { createUser } from "apis/user";
    2import { Header } from "common";

    Import statements become cleaner after aliasing.