Parsing the loader:

webpack.config.js:

module.exports = {
  module: {rules:[
      {
        test: /\.js$/
        use:[
        	'loader1'.'laoder2',
        	{
        		loader: 'loader3'.options: {}}]}}Copy the code

Loader is essentially a function:

module.exports = function (content, map, data){
  return content
}
module.exports.pitch = function(prevPath, nextPath){
  console.log(prevPath, nextPath)
}
Copy the code

Loaders can also mount a pitch method that executes from front to back, receiving the absolute path of the arguments before and after the loader executes.

Synchronous loader can be written in two ways

module.exports = function (content){
  // 1.return
  return content
  // 2.this.callback
  this.callback(null, content)
}
Copy the code

Asynchronous loader writing method: 1

module.exports = function(content){
  const callback = this.async()
  setTimeout(() = >{
    callback(null, content)
  },1000)}Copy the code

It is recommended to use an asynchronous loader to handle some things

Get the options passed to loader: loader-utils

Verify that options: schema-utils is passed to the loader. The verification rule is configuration schema.json

Loader3.js:

const {getOptions} = require('loader-utils')
const {validate} = require('schema-utils')
const schema = require('./schema')
module.exports = function(content){
  // Get the optionss passed in
  const options = getOptions(this)
  // Rule, parameter, rule error prompt
  validate(schema, options, {
    name:'loader3'})}Copy the code

Schema. Json:

{
  "type": "object"."properties": {
    "name": {
      "type": "string"."description": "Name"}}// Whether attributes other than name can be added during configuration
  "additionalProperties": false
}
Copy the code

Loader of actual combat:

NPM I loader-utils schema-utils @babel/ core@babel /preset-env -d

// Get the option passed in
const { getOptions } = require("loader-utils");
/ / check the options
const { validate } = require("schema-utils");
// This loader core: compile JS
const babel = require("@babel/core");
// NodeJS built-in utility function that uses its promisify to convert normal asynchronous functions to promise mode
const util = require("util");
// Check rules
const schema = require("./babelSchema");
// Babel's conversion rules
const transform = util.promisify(babel.transform);
module.exports = function (content) {
  / / get the options
  const options = getOptions(this);
  validate(schema, options, {
    name: "loader4"});const callback = this.async();
  transform(content, options)
    .then(({ code, map }) = > {
      callback(null, code, map);
    })
    // If the first parameter is present, the following parameters are not executed
    .catch((code) = > callback(code));
};
Copy the code

The config configuration:

...rules: [{test: /\.js$/,
    use: [
      {
        loader: "loader4".options: {
          presets: ["@babel/preset-env"[,},},],},]Copy the code