Webpack's imports-loader

      Give an official website address first, so you can see for yourself.

      https://www.webpackjs.com/loaders/imports-loader/

      Imports-loader is a very strange thing. Under the framework of webpack, if you write a js file, and then you want to write some code using jquery, then you need to import a jquery lib, and imports-loader's The effect is to save you from this process, so that you don't need to write such a sentence in the js file.

      (Quoted from the official website)

      Suppose you have  example.js this file

$("img").doSomeAwesomeJqueryPluginStuff();

      Then you can insert  $ variables into the module by configuring the imports-loader as follows:

require("imports-loader?$=jquery!./example.js");

      This will simply insert the  var $ = require("jquery"); prepend into  example.js .

      (end of quote)

      Next comes the key point. The principle of this loader is very simple. To put it bluntly, it is to add some code before and after the js file you want to import according to your url. You can take a look at the source code of imports-loader:

// 根据require的url生成一个object对象:
// URL : $=jquery&this=>window
// 生成:{"$" : "jquery", "this" : ">window"}
Object.keys(query).forEach(function(name) {
    var value;
    if(typeof query[name] == "string" && query[name].substr(0, 1) == ">") {
        /* ...省略部分 */
    } else {
        /* ...省略部分 */
        value = "require(" + JSON.stringify(mod) + ")";
    }
    if(name === "this") {
        /* ...省略部分 */
    } else if(name.indexOf(".") !== -1) {
        /* ...省略部分 */
    } else {
        // 生成一句代码,例如:var $ = require("jquery");
        // 然后将这行代码添加到数组中
        imports.push("var " + name + " = " + value + ";");
    }
});
// 数组转变成字符串,加在文件头
var prefix = HEADER + imports.join("\n") + "\n\n";
var postfix = "\n" + postfixes.join("\n");
/* ...省略部分 */
// 这个content就是你要导入的js文件里面的内容
return prefix + content + postfix;

      The most direct application scenario of imports-loader is that you want to import an open js file directly, instead of loading the class library through npm (there are some class libraries that do not support npm), and then the jquery used in this, You can try to import in this way.

     One of the most important prerequisites for using imports-loader, because the principle it implements is to require related class libraries, so remember:

In package.json, the corresponding class library must be written into devDependencies.

  "devDependencies": {
    /*...*/
    "jquery": "^3.3.1"
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516699&siteId=291194637