This is the 26th day of my participation in the August More Text Challenge.

1. Basic definitions

Loader acts as a “translator” to escape the read source file content into the new file content, and each Loader through the chain operation, the source file step by step to the desired shape.

2, writing ideas

  • 2.1) Loader writing should follow a single principle, each Loader only does one “escape” work, each Loader gets the content of the source file, can return the processed content by the way of output, can also call this.callback() method, To return the content to webpack, you can also use this.async() to generate a callback function that will output the processed content. In addition, Webpack also provides a set of tools for developing Loaders – loader-utils

  • 2.2) Compared with Loader, the compilation of Plugin is much more flexible. Webpack will broadcast many events during its running life cycle. Plugin can monitor these events and output results by changing the API provided by WebPack at the appropriate time

3, the preparation of matters needing attention

  • 3.1) Loader supports chain invocation, so the development needs to strictly follow the “single responsibility”, and each Loader is only responsible for what it needs to be responsible for

  • 3.2) Loader runs in Node. js. We can call any API provided by Node. js or install third-party modules

  • 3.3) The original content sent by Webpack to Loader is all strings encoded in UTF-8 format. When Loader processes binary files in some scenarios, You need to tell Webpack whether the Loader needs binary data via exports.raw = true

  • 3.4) Asynchronize Loader as much as possible. If the amount of calculation is small, synchronization can also be used

  • 3.5) Loader is stateless, we should not keep state in Loader

  • 3.6) Use the utilities provided for us by loader-utils and schema-utils

  • 3.7) Loading the local Loader method

4. Common Loaders

- 1File-loader: outputs a file to a folder and references the output file with a relative URL in the code2Url-loader: similar to file-loader, but can base64 file content into the code if the file is very small3Source-map-loader: loads additional sourcesMapFile to facilitate breakpoint debugging -4, image-loader: loads and compresses image files5Babel-loader: convert ES6 to ES5 -6, CSS-loader: loads the CSS and supports modularity, compression, and file import7Style-loader: inserts CSS code into JavaScript and loads CSS via DOM manipulation8Eslint-loader: Checks JavaScript code with ESLintCopy the code