A, the loader

1. The loader is introduced

What is the loader

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

Loader role

A Loader is like a translator in Webpack. Webpack only knows JavaScript, and other resources can be preprocessed by loader

  • Loaders are executed sequentially,Support for chained invocation. Loaders are executed from bottom to top and from right to left. Like files that deal with style classes,use:['style-loader', 'css-loader'].css-loaderThe processed file is returned tostyle-loader.
  • A Loader has a single responsibility and only needs to perform one conversion.
  • Webpack caches the processing results of all Loaders by default. Loaders that have not been modified will not be reloaded. If you disable Webpack, add the default cache resultsthis.cacheable(false);

Common loader

  • Loader for style classes:Css-loader, style-loader, less-loader, postCSs-loader (add -webkit)Etc.
  • Loader for file classes:url-loader, file-loader, raw-loaderAnd so on.
  • Loader to compile classes:babel-loader, ts-loaderEtc.
  • Check test class loader:eslint-loader, jslint-loaderEtc.

4. Three usage modes of loader

    1. inwebpack.config.jsIn the configuration
module.exports = {
    module: {rules: [{test:/\.css$/,
                use:['css-loader'].// use:{loader:'css-loader',options:{}}}}}]Copy the code
    1. Using command line parameters
webpack --module-bind 'css=css-loader'
Copy the code
    1. Use inline
import txt from 'css-loader! ./file.css';
Copy the code

2. Write a Loader

1. Loader is a function; 2. Convert the matched content. 3. Return the converted content. We can write the simplest loader according to this idea

/ / in. / loader/replaceLoader. Js loader to create a replacement string
module.exports = function(source) {
    return source.replace('a'.'b')}// Use your own loader in webpack.config.js
module.exports = {
    module: {rules: [{test:"/\.js$/".use: [{loader: path.resolve(__dirname, './loader/replaceLoader.js')
                    options: {name: 'Lin Yiyi'}}]}}// Or use replaceLoader
module.exports={
    resolveLoader: ['node_modules'.'./loader']
    module: {rules: [{test:"/\.js$/".use: ['resolveLoader']]}}}Copy the code

The above is the simplest example of writing a Loader

  • Loader can also receiveoptionsView the details of the parameters passed inloader API, you can also use the official onesloader-utilReceive parameters
const loaderUtil = require('loader-utils')
module.exports = function(source) {
    console.log(this.query.name) / / linyi
    const options = loaderUtil.getOptions(this)
    return source.replace('a'.'b')}Copy the code
  • Asynchronous: Loader is a function with synchronous and asynchronous distinction. Loaders that use asynchron need to be addedthis.async()Declare asynchronous operations
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)}Copy the code

The above code will wrap in 4 seconds, failing without the this.async() asynchronous operation, and the callback() callback will put the result back.

  • The default string encoding that Webpack passes to the Loader isutf-8If you need to handle binary files need to be addedexports.raw = true.
  • As mentioned above, WebPack will default toloaderThe load result cache is turned off if neededwebpackCache results need to be addedthis.cacheable(false);.
  • Npm linkSpecifically designed for developing and debugging native Npm modules that are not published to the Npm can also be native to the modalityloader. Specific needs inpackage.jsonIn the configurationLocal loader, run in the root directorynpm link loader-nameCan be found atnode_modulesIs used locallyloader. You can also use the one aboveresolveLoaderTo realize the importloaderThe way of

This section describes how to write loader

  1. Loader is an export function that returns a value and can be implemented using third-party modules and the Node API.
  2. Loader can useloader-utilsTo receiveoptionsThe parameter passed to the
  3. Loader asynchronously writes the declaration that needs to be displayedconst callback = this.async()Indicates asynchrony.
  4. Loader also needs to declare if it needs to process binary filesexports.raw = true
  5. Loader’s allowed results are cached by Webpack if neededwebpackCache results need to be declaredthis.cacheable(false)
  6. After writing the localloaderCan useNpm linkresolveLoaderThe import.

Ii. Webpack construction process

What does the webPack build process look like before we talk about plugins

  1. Initialization parameter. From the configuration file andshellThe merged parameters in the statement
  2. Begin to compile. Initialize the parameters obtained in the previous step toComplier object, load all import plug-ins, execute the object’s run method to start compiling;
  3. Determine the entrance. From the configuration of theentryEntry Find all entry files.
  4. Compile the module. Calls all configured based on the import file dependenciesloaderMake the transformation.
  5. Complete module compilation and output. According to the dependencies between the entry files, a code block is formedchunk.
  6. Output complete. The code block to be formedchunkOutput to the file system.

The complier objects initialized above will be injected into the plug-in’s Apply (complier). The complier object contains all the configuration information of the Webpack environment such as options, loaders, plugins and so on. It is easy to consider complier as an instance of Webpack. Events broadcast by Webpack can be listened to via compler.plugin().

Third, the plugin

Introduction to the plugin

What is the plugin

Plugin is a plug-in that is a class based on the event flow framework Tapable implementation. In the WebPack build process, all plugins are loaded and instances of plug-ins are created after the parameters are initialized.

The plugin function

Plugin can touch the entire event flow of webPack through hooks. That is, plugins can use the API provided by WebPack to do something with hooks that listen to these life cycles when appropriate.

Common plugin

  • html-webpack-pluginOne will be generated automatically after packaginghtmlFile, and will introduce the packaged JS file tohtmlWithin the file.
  • optimize-css-assets-webpack-pluginCompress the CSS code.
  • mini-css-extract-plugin. Will writestyleThe CSS inside the tag is separated into onelinkImport the generated CSS file
  • webpack-parallel-uglify-plugin. Enable multi-process execution code compression, improve packaging speed.
  • clean-webpack-plugin. Delete old generated files before each package.
  • serviceworker-webpack-plugin. Add offline caching for web applications.

How plugins are used

Use it in plugins

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

2. Write a plugin

Plugins are classes that provide built-in apis for plugins. You need to define the Apply (compliers) functions on top of your prototype. Also specify the Webpack hook to mount.

class MyPlugin {
    constructor(params){
        console.log(params)
    }
    // The reference function is called after webpack initializes the parameters, breaking into the initialized complier object.
    apply(complier){
         // Bind the hook event
        // complier.hooks.emit.tapAsync()
        compiler.plugin('emit'.compilation= > {
            console.log('MyPlugin')))}}module.export = MyPlugin
Copy the code

The compilation object contains the current module resources, compile-generated resources, and files that can listen for changes. After each file changes, a compilation object is generated, which can also be read into the Compiler object. Mode the plugin you can use the node mode tool in the package. The json add “debug” : “node, inspect, inspect BRK node_modules/webpack/bin/webpack js.” “

Summarize the idea of writing plugin

  1. Write a class class.
  2. Define an apply method in your class.
  3. In application methodapply()Specified inwebpackEvent hookscomplier.hooks..
  4. Handles specific data for webPack internal instances.
  5. The callback provided by WebPack is invoked when the functionality is complete.

4. Interview questions

1. Difference between Loader and plugin

  1. Loader is a function that processes a specific module, converts the received content, and returns it. inwebpackTo manipulate files and act as file converters. inmodules.rulesIn the configuration.
  2. Plugin is a plug-in that does not manipulate files directly and is based on an event flow frameworkTapableThe implementation,pluginIt can be accessed through hookswebpackThe whole process of events. That is to say,pluginYou can use hooks that listen to these lifecycles when appropriatewebpackProvides apis to do something. inpluginsConfigure plug-ins in

2. How to write loader

Participate in

3. Writing ideas of Plugin

Participate in

4. Difference between complier and compilation

  1. The Complier object exposes the entire webpack lifecycle related hook, yeswebpackThe product of the initialization parameter containsoptions, entry, pluginsAnd other attributes can be simply understood aswebpackAn instance of.
  2. compilationThe object iscomplierThe instance is every timewebpackLifecycle objects in the build process. One is generated for each file that changescomplitionObject.

Summary: Both objects have their own lifecycle hooks, and the compilation object is responsible for smaller lifecycle hooks. Compiler objects are webpack’s entire lifecycle hooks.

reference

Introduction to Webpack loader and Plugin

Webpack build process

Webpack loader and plugin

Deep into Webpack- write Loader