Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is require.resolve in webpack loader test

Tags:

webpack

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?
like image 328
Nicolas S.Xu Avatar asked Jun 29 '16 17:06

Nicolas S.Xu


People also ask

What is require context?

require. context. You can create your own context with the require. context() function. It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

Why do you need a loader for webpack?

They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs.

How do you activate a webpack loader?

You can easily write your own loaders using Node. js. Loaders are activated by using loadername! prefixes in require() statements, or are automatically applied via regex from your webpack configuration – see configuration.


1 Answers

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

like image 186
maksimr Avatar answered Oct 20 '22 04:10

maksimr