Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 8, 2021 11:16 am GMT

Super simple imports with Webpack resolve

Modules were, without a dought, one of the best improvements that came with ES6. When combined with Webpack, it allows us to write code in a more developer-friendly way. But file referencing when importing can sometimes become repetitive, error-prone, and hard to look at. Luckily Webpack has us covered with the right solution that is super easy to configure.

Webpack resolve

Resolve is a Webpack library that helps locate imported modules. To configure it, add the code snippet below to the config file.

webpack.config.js

module.exports = {  resolve: {    // configuration options  },};

Resolve library allows us to resolve imports in two ways: with modules or alias.

Modules

Modules resolve imports by searching for them in the specified directories. Often this is used to resolve node modules.

webpack.config.js

resolve: {  modules: ['node_modules']}

This configuration allows us to replace this:

import Module from '../../../../node_modules/module';

with this:

import Module from 'module';

Using resolve.modules, this is all you have to do to make imports work since it will not cause issues with other config files.

Alias

Alias resolves imports by replacing the original path with the custom one.

webpack.config.js

resolve: {  alias: {    @components: path.resolve(__dirname, 'components/'),    @partials: path.resolve(__dirname, 'partials/'),  },}

This allows us to change this:

import Component from '../../../../components/component';import Part from '../../../../partislas/part';

to this:

import Component from '@components/component';import Part from '@partials/part';

Note that __dirname points to the location of the webpack.config.js file.

ESLint adjustment

Using an alias you might get an ESLint error saying the path cant be resolved. To fix that you can use eslint-import-resolver-webpack.

To configure it you can add this line of code to the .eslintrc.yml file:

settings:  import/resolver: webpack

This setting will work if a webpack.config.js is in the same directory as the eslintrc.yml file. Otherwise, see other settings options.

Summary

Configuring Webpack can be overwhelming with all the available options but luckily, this library is very simple to understand and configure. It helped me to write cleaner imports, and I am sure you will find it as useful as I have.


Original Link: https://dev.to/tjasa/super-simple-imports-with-webpack-resolve-150

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To