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()
:
Before I always put the loader name directly like this:
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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With