Home  >  Article  >  Web Front-end  >  Detailed explanation of loader mechanism of webpack source code

Detailed explanation of loader mechanism of webpack source code

亚连
亚连Original
2018-05-26 14:31:111565browse

This article mainly introduces the detailed explanation of the loader mechanism of the webpack source code. Now I will share it with you and give you a reference.

Loader concept

Loader is used to load and process various forms of resources. It is essentially a function that accepts files as parameters and returns the converted structure.

loader is used to convert the source code of the module. Loaders allow you to preprocess files when importing or "loading" modules. Therefore, loaders are similar to "tasks" in other build tools and provide a powerful way to handle front-end build steps. Loaders can convert files from different languages ​​(such as TypeScript) to JavaScript, or inline images to data URLs. The loader even allows you to import CSS files directly in JavaScript modules!

The difference between loader and plugin

The plugin mechanism was introduced in the previous article, and the loader, the object of today’s study, together they are greatly Expanded the functionality of webpack. The difference between them is that the loader is used to convert the source code of the module, while the purpose of the plug-in is to solve other things that the loader cannot achieve. Why do you say so much? Because the plugin can be called at any stage, it can further process the output of the Loader across the Loader, trigger events during the build run, execute pre-registered callbacks, and use the compilation object to do some lower-level things.

loader usage

Configuration

module: {
  rules: [
   {
    test: /\.css$/,
    use: [
     { loader: 'style-loader' },
     {
      loader: 'css-loader'
     }
    ]
   }
  ]
 }

Inside Link

import Styles from 'style-loader!css-loader?modules!./styles.css';

CLI

webpack --module-bind 'css=style-loader!css-loader'

Instructions The above three usage methods all execute a set of chained loaders in order from right to left. The first loader in the loader chain returns the value to the next loader. First use css-loader to parse the css content specified in the @import and url() paths, and then use style-loader to insert the original CSS code into a style tag in the page.

loader implementation

##

//将css插入到head标签内部
module.exports = function (source) {
  let script = (`
   let style = document.createElement("style");
   style.innerText = ${JSON.stringify(source)};
   document.head.appendChild(style);
  `);
  return script;
}
//使用方式1
resolveLoader: {
  modules: [path.resolve('node_modules'), path.resolve(__dirname, 'src', 'loaders')]
},
{
  test: /\.css$/,
  use: ['style-loader']
},
//使用方式2
//将自己写的loaders发布到npm仓库,然后添加到依赖,按照方式1中的配置方式使用即可

Description The above is a simple loader implementation, executed in a synchronous manner. It is equivalent to realizing the function of style-loader.

Loader principle

##
function iteratePitchingLoaders(options, loaderContext, callback) {
  var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
  // load loader module
  loadLoader(currentLoaderObject, function(err) {
    var fn = currentLoaderObject.pitch;
    runSyncOrAsync(
      fn,
      loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}],
      function(err) {
        if(err) return callback(err);
        var args = Array.prototype.slice.call(arguments, 1);
        if(args.length > 0) {
          loaderContext.loaderIndex--;
          iterateNormalLoaders(options, loaderContext, args, callback);
        } else {
          iteratePitchingLoaders(options, loaderContext, callback);
        }
      }
    );
  });
}

Description The above are the key steps of loader execution in the webpack source code, the recursive way Executing the loader, the execution process is similar to the express middleware mechanism

The above is what I compiled for everyone, I hope it will be helpful to everyone in the future.

Related articles:

Jquery specific examples introduce when to use AJAX and where AJAX should be used


js ajax Progress bar code when loading


Two solutions to Ajax cross-domain issues


The above is the detailed content of Detailed explanation of loader mechanism of webpack source code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn