Loader basis

Since Webpack runs on Node.js, a Loader is essentially a Node.js module that needs to export a function.

A simple Loader source is as follows:

Module.exports = function(source) {// source is the original content of a file passed to the Loader. The Loader does not convert any return source. };Copy the code

Get Loader options

Loader-utils built into Webpack helps you get the options configuration passed in to control the Loader

const loaderUtils = require('loader-utils'); Module.exports = function(source) {// getOptions from user to current Loader const options = loaderutils.getoptions (this); return source; };Copy the code

Synchronous and asynchronous

Loaders can be synchronous or asynchronous. The preceding loaders are all synchronous. There are scenarios where the transformation step needs to be done asynchronously, such as network requests.

Module.exports = function(source) {var callback = this.async(); // module.exports = function(source) {var callback = this.async(); SomeAsyncOperation (source, function(err, result, sourceMaps, ast) {// Callback (err, result, sourceMaps, ast); }); };Copy the code

More loader API references

In actual combat

Log (XXXX) to console.log(‘hello world’)

1. Create a my-loader file

Js: in the index.

module.exports = function (source) {
  
  return source.replace(/console\.log\(.+\)/, "console.log('hello world')");
    
};
Copy the code

2. Use the local customized my-loader

ResolveLoader is used to configure how Webpack finds the Loader. By default, only node_modules is searched, and resolveloader.modules needs to be modified in order for Webpack to load the Loader placed in the local project. Webpack. Config. Js:

const path = require('path'); module.exports = { entry:{ index:'./src/index.js', }, module: { rules: [ { test: /\.js$/, use: ['my-loader'], // use custom loader}]}, resolveLoader:{ [path.resolve(__dirname,'./loader/'),'node_modules'], }, };Copy the code

A custom loader is created