“This is my fourth day of participating in the First Challenge 2022. For more details: First Challenge 2022.”

Earlier we looked at output and entry for webpack. Webpack only has the ability to process JS and JSON files. If you want to process other files, you must use loader. Let’s take a look at how WebPack uses loader to handle files other than JS and JSON.

Loader

As mentioned above, loader is used to process files other than JS and JSON and convert them into valid modules. So let’s take a look at how loader works.

Using the loader

There are two ways to use loader:

  1. Configuration method: Define loader in the WebPack configuration file. For example, configure loader to parse the CSS in the configuration file as follows:
    // webpack.config.js
    module.exports = {
      mode: 'development'.entry: getEntry,
      output: {
        filename: '[name].bundle.js'.chunkLoadingGlobal: 'var test1 = 111',},module: {
        rules: [{test: /\.css$/,
            use: [
              { loader: 'style-loader' },
              { loader: 'css-loader'}],},],},};Copy the code

    In the code above,moduleFields are used to determine how WebPack handles different types of modules in a project.[Module fully configured].

    testIt can be a regular expression or a string to match the corresponding file.

    useRepresents the matched file using the followingloader, note that the loader execution order isFrom down to upThe execution.

  2. Inline: import from each file
    import Styles from 'style-loader! css-loader? modules! ./styles.css';
    Copy the code

Writing a loader

After explaining how to use loader, let’s see how to write a loader.

  • For example, write a loader that matches all js files and injects code into them.
// entry.js
function test1() {
  console.log('test1');
  console.log(inject);
}
test1();

// entry1.js
function test2() {
  console.log('test2');
  console.log(inject);
}
test2();

// loader/inject.js
module.exports = function (source) {
  console.log(source);
  return `
    var inject = 'inject code';
    ${source}
  `;
};


// webpack.config.js
const path = require('path')
module.exports = {
  mode: 'production'.entry: {
    app: path.resolve(__dirname, 'src'.'entry.js'),
    lib: path.resolve(__dirname, 'src'.'entry1.js'),},output: {
    filename: '[name].bundle.js',},module: {
    rules: [{test: /\.js$/,
        use: [{ loader: path.resolve(__dirname, 'loader'.'inject')}],},],},};Copy the code

Run the Webpack output

// app.bundle.js
console.log("test1"),console.log("inject code");

// lib.bundle.js
console.log("test2"),console.log("inject code");
Copy the code
  • As you can see from the code above, we inject a value ofinject codeAll variables are injected into the packagetestIn the matched file.
  • The loader function needs to receive an argument for the matched filestringFormal output, after getting the file data, we can modify or expand the data, and finally return the processed data.
  • If multiple Loaders exist, the loader executes the data from bottom to top. The upper-layer loader receives the data processed by the lower-layer loader.

Loader features

Let’s take a look at the loader features and write some more complex loaders according to the features.

  • Chain calls are executed by the loader from the bottom up
  • Loader methods can be synchronous or asynchronous
  • Loader runs in Node. js and can perform any operations, including but not limited to file I/O operations, operating on the operating system, and process creation.

summary

This section focuses on the Loader in the basic webPack configuration

  • loaderIs used to process files that WebPack cannot handle on its own, and it is theoretically possible to process all files by writing a Loader.
  • loaderIs a function that takes a string of matched files and outputs the processed data (string).
  • loaderHave chain call; Synchronous/asynchronous invocation; A feature that executes in Node and allows you to do anything.

This article is the third in a series on learning Webpack from Scratch. Additional chapters can be found at 👇 :

Learn webPackage 5.x from scratch (1) Learn webpackage 5.x from scratch (2) Learn Webpackage 5.x from scratch (3) Learn Webpackage 5.x from scratch (4) Learn WebPackage 5.x from scratch (5)