首页 > 其他分享 >【前端必会】webpack 插件,前进路绕不过的障碍

【前端必会】webpack 插件,前进路绕不过的障碍

时间:2022-09-25 17:55:24浏览次数:75  
标签:__ function 插件 require exports js webpack 路绕

背景

  1. webpack的使用中我们会遇到各种各样的插件、loader。
  2. webpack的功力主要体现在能理解各个插件、loader的数量上。理解的越多功力越深

开始

https://webpack.docschina.org/api/compilation-hooks/
https://webpack.docschina.org/api/compiler-hooks/
http://www.icodebang.com/article/232889

  1. 开发一个自定义的插件HelloWordPlugin
//HelloWordPlugin.js
const { Compilation } = require("webpack");
class HelloWorldPlugin {
  constructor() {}
  apply(compiler) {
    console.log(compiler);
    let outputFileName = compiler.options.output.filename
    compiler.hooks.thisCompilation.tap("HelloWorldPlugin", (compilation) => {
      console.log(compilation);
      //   debugger

      compilation.hooks.processAssets.tap(
        {
          name: "HelloWorldPlugin",
          stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
          additionalAssets: true,
        },
        (assets) => {
          assets[outputFileName]._source._children.forEach((item, i) => {
            if (
              typeof item === "string" &&
              item.indexOf("var __webpack_exports__") === 0
            ) {
              assets[outputFileName]._source._children[i] = item +=
                "var HelloInjectCode = {}; \n";
            }
          });
        }
      );
    });
  }
}
module.exports = HelloWorldPlugin;

//测试主文件,主要加载创建webpack 配置、实例、执行

//index.js
const webpack = require("webpack");
const path = require("path");
const HelloWorldPlugin = require("./HelloWorldPlugin");
const config = {
  context: path.resolve(__dirname),
  mode: "production",
  optimization: {
    minimize: false,
  },
  entry: "./main.js",
  target: ["web", "es5"],
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname,"dist"),
  },
  plugins: [new HelloWorldPlugin()],
};

const compiler = webpack(config);
compiler.run((err, stats) => {
  console.log(err);
  console.log(
    stats.toJson({
      files: true,
      assets: true,
      chunk: true,
      module: true,
      entries: true,
    })
  );
});

  1. 两个项目文件,基本还是之前的例子
//main.js
import { max, PI1,PI3 } from "../webpack-modules/index";
!(function () {
  console.log(max(1, 2), PI1,PI3);
})();

//../webpack-modules/index
let PI1 = 3.1415926;
let PI2 = 3.1415926;

function max(a, b) {
  return a > b ? a : b;
}
console.log(PI2);
export { max, PI1 };

  1. 生成的文件
//dist/bundle.js
/******/ (function() { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The require scope
/******/ 	var __webpack_require__ = {};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	!function() {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = function(exports, definition) {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	}();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	!function() {
/******/ 		__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ 	}();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	!function() {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = function(exports) {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	}();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
var HelloInjectCode = {}; 

// NAMESPACE OBJECT: ../webpack-modules/index.js
var webpack_modules_namespaceObject = {};
__webpack_require__.r(webpack_modules_namespaceObject);
__webpack_require__.d(webpack_modules_namespaceObject, {
  "X": function() { return PI1; },
  "F": function() { return max; }
});

;// CONCATENATED MODULE: ../webpack-modules/index.js
let PI1 = 3.1415926;
let PI2 = 3.1415926;

function max(a, b) {
  return a > b ? a : b;
}
console.log(PI2);


;// CONCATENATED MODULE: ./main.js

!(function () {
  console.log(max(1, 2), PI1,webpack_modules_namespaceObject.PI3);
})();

/******/ })()
;

总结

  1. 使用compilation.hooks.processAssets可以处理生成的资源
  2. 多看文档
  3. 开发插件,相当于是开发一个nodejs的工程,文件入口(测试验证用)可以直接使用webpackAPI ,参考index.js
  4. compiler更多面向编译配置,compilation更多面向编译是的资源,更多体现在watch上,每次watch或生成一个compilation
  5. 该插件向入口代码中插入了自定义的代码。一行helloworld,千言万语尽在不言中

标签:__,function,插件,require,exports,js,webpack,路绕
From: https://www.cnblogs.com/lee35/p/16728337.html

相关文章