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 can’t 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.
Top comments (1)
Then you can use a jsconfig.json file and set the
compilerOptions.path
array to resolve those paths in order to recover the support for intellisense in those imports :)