Write loader and plugin

Time:2022-5-11

Original address

Write loaders and plugins

github

1、 Loader

1. Introduction to loader

What is loader

Loader is actually a function that converts the matched content and returns the converted result.

Loader function

staywebpackinloaderLike a translator.webpackOnly knowJavaScriptThis language is used for other resourcesloaderIt can be transformed for pretreatment

  • The loader is executed in order,Support chained call。 The order of loader execution is from bottom to top and from right to left. For example, processing files of style classes,use:['style-loader', 'css-loader']css-loaderThe processed file is returned tostyle-loader
  • The responsibility of a loader is single, and only one transformation needs to be completed.
  • Webpack will cache the processing results of all loaders by default, and the loaders that have not been modified will not be reloaded. The default cache results of closing webpack need to be addedthis.cacheable(false);

Common loaders

  • Loader of style class:CSS loader, style loader, less loader, postcss loader (add WebKit)etc.
  • Loader of file class:url-loader, file-loader, raw-loaderWait.
  • Loader of compilation class:babel-loader, ts-loaderetc.
  • Verification test class loader:eslint-loader, jslint-loaderetc.

4. Three ways of using loader

    1. staywebpack.config.jsMedium configuration

      module.exports = {
        module:{
         rules:[{
                 test:/\.css$/,
                 use:['css-loader'],
                 // use:{loader:'css-loader',options:{}}
             }
         ]
        }
      }
    1. Through the parameter mode of the command line

      webpack --module-bind 'css=css-loader'
    1. Use inline

      import txt from 'css-loader!./file.css';

2. Write a loader

Idea: as we said earlier1. Loader is a function; 2. Convert the matched content; 3. Return the converted content, according to this idea, we can write the simplestloader

//Yes/ loader/replaceLoader. JS creates a loader that replaces the string
module.exports = function(source) {
    return source.replace('a', 'b')
}

//On webpack config. JS uses its own loader
module.exports = {
    module:{
        rules:[{
            test:"/\.js$/",
            use:[{
                    loader: path.resolve(__dirname, './loader/replaceLoader.js')
                    options:{
                        Name: 'Lin 11'   
                    }
                }
            ]
        }]
    }
}

//Or use replaceloader
module.exports={
    resolveLoader:['node_modules', './loader']
    module:{
        rules:[{
            test:"/\.js$/",
            use:['resolveLoader']
        }]
    }
}

The above is the simplest case of writing loader

  • The loader can also receiveoptionsThe parameters passed in. See the detailsloader API, you can also use the officialloader-utilReceive parameters

    const loaderUtil = require('loader-utils')
    module.exports = function(source) {
      console. Log (this. Query. Name) // Lin 11
      const options = loaderUtil.getOptions(this)
      return source.replace('a', 'b')
    }
  • Asynchronous: loader is a function. Naturally, there is a distinction between synchronous and asynchronous. Using asynchronous loaders requires addingthis.async()Declare asynchronous operation

    const loaderUtils = require('loader-utils')
    module.exports = function(source) {
      const options = loaderUtils.getOptions(this)
      const callback = this.async()
      setTimeout(()=>{
          console.log(options.name)
          let res = source.replace('a', options.name)
          callback(null, res, sourceMaps, ast)
      }, 4000)
    }

    The above code will be packaged successfully in 4 seconds. If notthis.async()The asynchronous operation will fail,callback()The callback function puts the result back.

  • By default, the string code passed by webpack to the loader isutf-8, if you need to process binary files, you need to addexports.raw = true
  • As mentioned above, webpack will default toloaderThe load result cache of is closed if necessarywebpackThe cached results need to be addedthis.cacheable(false);
  • Npm linkIt is specially used to develop and debug the local NPM module. It can also be in the local mode without publishing it to NPMloader。 Specific needs inpackage.jsonMedium configurationLocal loader, execute under the root directorynpm link loader-nameCan be innode_modulesUse local inloaderYes. At the same time, the above method can also be usedresolveLoaderImplement importloaderWay of

Summarize the idea of writing loader

  1. Loader is an export function with return value, which can be implemented with the help of third-party modules and node APIs.
  2. Loader can useloader-utilsReceivedoptionsParameters passed from
  3. The asynchronous writing of loader requires the declaration to be displayedconst callback = this.async()Indicates asynchrony.
  4. If the loader needs to handle binary files, it also needs to declareexports.raw = true
  5. The allowed results of the loader will be cached by the webpack and closed if necessarywebpackThe cache result of needs to be declaredthis.cacheable(false)
  6. Written localloaderCan helpNpm linkorresolveLoaderImport.

2、 Construction process of webpack

Before talking about plugins, you need to know what the construction process of webpack is

  1. Initialization parameters。 From profiles andshellMerged parameters in statement
  2. Start compilation。 Initialize the parameters obtained in the previous step toComplier object, load all import plug-ins, execute the run method of the object and start compiling;
  3. Determine the entrance。 From configuredentryThe portal finds all the portal files.
  4. Compilation module。 Call all configured according to the dependency of the entry fileloaderConvert.
  5. Complete module compilation and output。 Code blocks are formed according to the dependencies between entry fileschunk
  6. Output complete。 Code block to be formedchunkOutput to file system.

Formed by initialization abovecomplierObject will be injected into the plug-inapply(complier)Inside.complierThe object contains all the configuration information of the webpack environment, such asoptions, loaders, pluginsAnd so on, you can simply thinkcomplierIs an instance of webpack, which can be accessed throughcompler.plugin()Can monitorwebpackBroadcast events.

3、 Plugin

1. Introduction to plugin

What is a plugin

Plugin is a plug-in, which is a class based on the event flow frameworkTapablerealization. In the construction process of webpack, after initializing the parameters, all the parameters will be loadedpluginPlug in, create an instance of the plug-in.

Plugin function

pluginIt can be involved through the hookwebpackThe whole event flow. in other wordspluginYou can use these life cycle hooks at the right timewebpackThe provided API does something.

Common plugins

  • html-webpack-pluginWill automatically generate one after packaginghtmlFile, and the packaged JS file will be imported intohtmlIn the document.
  • optimize-css-assets-webpack-pluginCompress CSS code.
  • mini-css-extract-plugin。 Will writestyleThe CSS in the tag is separated into onelinkImport the generated CSS file
  • webpack-parallel-uglify-plugin。 Enable multi process code compression to improve the speed of packaging.
  • clean-webpack-plugin。 Delete the old generated files before each package.
  • serviceworker-webpack-plugin。 Add offline caching function for web applications.

How to use plugin

staypluginsUsed in

const ServiceworkerWebpackPlugin = require('serviceworker-webpack-plugin')
module.exports = {
    plugins:[
        new ServiceworkerWebpackPlugin(),
    ]
}

2 write a plugin

Idea:pluginsIs a class,webpackThere are many built-in for pluginapi, it needs to be defined on the prototypeapply(compliers)Function. Also specify the to mountwebpackHook.

class MyPlugin {
    constructor(params){
        console.log(params)
    }
    //After webpack initializes the parameters, it will call this reference function to break into the initialized complier object.
    apply(complier){
         //Bind hook event
        // complier.hooks.emit.tapAsync()
        compiler.plugin('emit', compilation => {
            console.log('MyPlugin')
        ))
    }
}
module.export = MyPlugin

Compilation objectIt contains the current module resources, compilation generation resources, and files that can monitor changes. After each file changes, acompilationObject, bycompilationCan also readcompilerObject.
modepluginYou can use node’s modal tool topackage.jsonAdd in"debug":"node --inspect --inspect brk node_modules/webpack/bin/webpack.js"

Summarize the idea of writing plugin

  1. Write a class.
  2. Define an apply method in the class.
  3. In application methodapply()Specified mounted inwebpackevent hook complier.hooks.
  4. Process specific data for webpack internal instances.
  5. Call the callback provided by webpack after the function is completed.

4、 Interview questions

1. The difference between loader and plugin

  1. Loader is a function used to match a specific module, convert the received content and return it. staywebpackOperate files in and act as a file converter. staymodules.rulesConfiguration in.
  2. Plugin is a plug-in that does not directly manipulate files and is based on the event flow frameworkTapablerealization,pluginIt can be involved through the hookwebpackThe whole event flow. in other wordspluginYou can use these life cycle hooks at the right timewebpackThe provided API does something. staypluginsConfiguring plug-ins in

2. Writing ideas of loader

Ginseng

3. Writing ideas of plugin

Ginseng

4. Difference between complier and compilation

  1. The complier object exposes the hooks related to the whole life cycle of the webpack, which iswebpackThe product of initialized parameters, includingoptions, entry, pluginsAnd other attributes can be simply understood aswebpackAn example of.
  2. compilationObject iscomplierAn example is every timewebpackLifecycle objects in the build process. One can be generated after each file changescomplitionObject.
    Summary: both objects have their own life cycle hooks,Compilation objectResponsible for smaller granularity life cycle hooks.Compiler objectIt is the object of a whole life cycle hook of webpack.

reference resources

Introduction to loader and plugin of webpack

Webpack build process

Written by webpack loader and plugin

Go deep into webpack – write loader

Recommended Today

Solution to the problem of native PAGE compatibility with IE9

preface Recently, I received a customer’s native page. The customer requires that the page must be compatible with IE9 and above browsers, and the compatibility mode of 360 browser can be accessed normally. 360 browser can force speed mode through code, which is easy to solve. However, to be compatible with IE9, many CSS3 properties […]