How to import react components from webpack alias [2021 tutorial]

import MyLibrary from '@my-libraries';

I am sure you have encountered similar import declarations when using npm libraries.

There is basically no difference between the following:

import MyLibrary from './../../MyLibrary.js';
import MyLibrary from '@my-libraries';

Well, technically, there is a difference. And the difference being is that it looks prettier, isn’t it?

(I am not saying that it is complicated, because the imports are handled by IDEs that I hope you are using)

How to set this up

This is being done via webpack configuration file and the directive resolve.alias.

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

module.exports = {
    entry: [],
    resolve: {
        alias: {
            '@my-custom-ui-kit': path.resolve(__dirname, 'resources/jsx/components'),
        }
    },
};

Once you set up the above alias (also you need to alter the path into the folder where your components reside) you can start using import declaration like so:

import MyLibrary from '@my-custom-ui-kit';
import MyComponent from '@my-custom-ui-kit/custom-component';

One important thing to note is how you should name your components in the component directory. It can be done as follows:

  • MyLibrary.js
  • MyLibrary/index.js

Wrapping up

In this tutorial I showed you how you can easily create an alias for your imports so as your code can be more polished, more cleaner and readable. WebPack has got many more possibilities of aliases and I recommend checking out the official article on the topic: https://webpack.js.org/configuration/resolve/ .

Sources:

Credits:

Leave a comment

Your email address will not be published. Required fields are marked *