3

I'm using a React template and I am currently very confused by this one line, for multiple reasons.

require('file-loader?name=[name].[ext]!./index.html');
  1. First, why is file-loader being required in the entry point app file?
  2. What is the name=[name] parameter doing?

  3. What does the exclamation point mean?

Michael Du
  • 669
  • 7
  • 15

1 Answers1

2

This is an example of a Webpack loader (in this case file-loader) being used inline.

When a Webpack loader is used inline, rather than via an object in a Webpack configuration file's module.rules array, the name of the loader to be used is prepended to the name of the file you want to require (or import), separated by a !. Any options to be passed to the loader are specified after the loader's name as either a query string or a JSON string, with a ? separating the loader name and loader options.

Given that file-loader copies a file to your Webpack output directory and returns its URL, require("file-loader?name=[name].[ext]!./index.html") copies ./index.html to the output directory with its original name and extension. If the result of calling require was assigned to any variable, in this case it would return /index.html (prefixed with a public path if set in your Webpack configuration file).

All of this is Webpack specific - if you tried to run this code in Node.js without putting it through Webpack, you would almost certainly get an error.

Thomas Foster
  • 1,303
  • 1
  • 10
  • 23