Home > Web Front-end > JS Tutorial > body text

Instructions for using loader mechanism in webpack source code

php中世界最好的语言
Release: 2018-05-02 10:38:50
Original
1370 people have browsed it

This time I will bring you the instructions for using the loader mechanism in the webpack source code. What are the precautions for using the loader mechanism in the webpack source code. The following is a practical case, let's take a look.

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. A loader allows you to pre-process files when importing or "loading" a module. Therefore, loaders are similar to "tasks" in other build tools and provide a powerful way to handle front-end build steps. The loader can convert files from different languages ​​(such as TypeScript) to JavaScript, or convert inline images into 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 have greatly expanded webpack function. 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'
     }
    ]
   }
  ]
 }
Copy after login

Inline

import Styles from 'style-loader!css-loader?modules!./styles.css';
Copy after login
CLI

webpack --module-bind 'css=style-loader!css-loader'
Copy after login
Explain that the above three methods of use are to 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 on 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中的配置方式使用即可
Copy after login
Description The above is a simple loader implementation, executed in a synchronous manner, which 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);
        }
      }
    );
  });
}
Copy after login
Description The above are the key steps for loader execution in the webpack source code. The loader is executed recursively. The execution process is similar to express

middlewareMechanism

Reference source code

  1. webpack: "4.4.1"

  2. ##webpack- cli: "2.0.13"
  3. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

JS analysis of steps to implement dynamic progress bar


js css to achieve typing effect with controllable speed on the page

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!