Home >Web Front-end >JS Tutorial >Detailed explanation of practical cases of webpack+loader

Detailed explanation of practical cases of webpack+loader

php中世界最好的语言
php中世界最好的语言Original
2018-06-11 13:49:091182browse

This time I will bring you a detailed explanation of the practical case of webpack loader. What are the precautions for practical use of webpack loader? 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. 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 previous article introduced the plugin mechanism, 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'
     }
    ]
   }
  ]
 }

Inline

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

CLI

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

Explain that the above three usage methods 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 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, 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);
        }
      }
    );
  });
}

Explain that 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 the express middleware mechanism

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:

Vue Sortable project practical code

How to apply response writeback to render the page

The above is the detailed content of Detailed explanation of practical cases of webpack+loader. 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