15

I am learning this imports-loader on webpack. I've already built several webpack demo projects by following tutorials.

Here is the code to configure imports-loader:

// ./webpack.config.js

module.exports = {
    ...
    module: {
        loaders: [
            {
                test: require.resolve("some-module"),
                loader: "imports?this=>window"
            }
        ]
};

My questions:

  1. Normally, the "test" should be a regex expression. What is the require.resolve("some-module") here? what does it mean?
Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129

2 Answers2

24

require.resolve("<moduleName>") returns string which contains path to the module, for example

> require.resolve('angular')
/tmp/node_modules/angular/index.js

so in your example property test will contain string with path to the module some-module, by default webpack converts string to the regular expression so final version of loader config will be something like this:

{
  test: /^node_modules\/some-module\/index.js/,
  loader: 'imports?this=>window"
}

as you can see this loader will be applied only for one file

sam
  • 40,318
  • 2
  • 41
  • 37
maksimr
  • 4,891
  • 2
  • 23
  • 22
  • What exactly is the reason for using require.resolve() over just passing a string for things like loaders? – EJ Mason Oct 23 '20 at 18:10
  • 2
    @EJMason if you pass just a name like "foo" you never know relative to which folder web pack would resolve this name. For example you have an npm library which should be builded by web pack by the client app and ship it through npm. When client would build you library and use your webpack.config `pwd` would be client project dir so "foo" would be resolved relative to this folder. It means that there are chance that 1. web pack just does not find such loader 2) It resolve client version of such loader – maksimr Oct 24 '20 at 10:47
0

webpack's require.resolve returns module id - webpack.js.org/api/module-methods/#require-resolve

Module ID is a number in webpack (in contrast to NodeJS where it is a string -- the filename).

Paul Seleznev
  • 672
  • 1
  • 11
  • 24