Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of using require.resolve in Webpack config rules?

So I was checking the webpack config file generated by create-react-app, when I noticed that when specifying the loaders to use, it uses require.resolve():

enter image description here

Before I always put the loader name directly like this: enter image description here

According to the documentation require.resolve() gets the id and compiles it to the path of the module. But still, I'm not sure what exactly is the difference between these two approaches, since they both work. Is it because CRP wraps the config files in a single folder so it is required to resolve the path of the module? Or are there any other reasons?

like image 241
sq29 Avatar asked Oct 01 '18 08:10

sq29


1 Answers

This approach is used in CRP since v1.0.0. See the PR for example. I don't think you should care about it until you build a project with subprojects.

It does make sense when you have a complex project. If you specify a loader using string name, it will be resolved related to the root project. But when you specify it using require.resolve it will be resolved related to the config, not to the root application.

root
├─┬ project1
│ ├─┬ node_modules
│ │ ╰── awesome-typescript-loader
│ ╰── webpack.config.js
├─┬ project2
│ ├── node_modules
│ ╰── webpack.config.js
├── node_modules
╰── webpack.config.js

root/webpack.config.js:

module.exports = [
  require('./project1/webpack.config.js'),
  require('./project2/webpack.config.js'),
];

In the example above awesome-typescript-loader is only installed for project1. So let's run webpack from the root project.

root/project1/webpack.config.js:

// It throws "Can't resolve 'awesome-typescript-loader'" error
loader: 'awesome-typescript-loader',
// It works
loader: require.resolve('awesome-typescript-loader')
like image 145
Alexey Prokhorov Avatar answered Oct 19 '22 23:10

Alexey Prokhorov