Webpack - 编写一个移除Console的Loader

开发 · 2023-11-21 · 45 人浏览

编写一个移除生产环境下的console的Loader函数

一些知识点

cacheable

Webpack5中用于确定是否有缓存功能,并启用

getOptions

Webpack5中用于获取传入的参数

异步/同步

同步直接返回修改好的内容即可,异步即用到async函数

const callback = this.async();
  //遇到异步loader后会等待执行 完成了才会继续往下走
  // 等到callback的执行
  setTimeout(() => {
    callback(null, content);
  }, 1000);

更快捷的确定Loader位置

const path = require("path");
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ["loader1", "loader2", "loader3"], //从后往前执行
      },
    ],
  },
  // 解析loader的规则
  resolveLoader: {
    modules: ["node_modules", path.resolve(__dirname, "loaders")],
  },
};

参数校验

如果有对参数校验的前提,可以引入JSON校验的包来做这件事

const { validate } = require("schema-utils"); //校验json和 options是否一致
const schema = require("./schema.json");

module.exports = function (content, map, meta) {
  const rawOp = this.getOptions(); //提供获取选项的函数 webpack提供
  // 校验Object是否符合json,json参数,选项options,可选配置 提示是哪个loader出问题
  validate(schema, rawOp, {
    name: "loader3",
  });
  return content;
};
{
    "type":"object",
    "properties":{
        "name":{
            "type":"string",
            "description":"名称"
        }
    },
    "additionalProperties":true  是否允许添加其他属性
}

完整实现

module.exports = function CleanConsoleLoader(content) {
  // Cache check
  this.cacheable && this.cacheable();
  // Get options
  const rawOptions = this.getOptions();

  const { enable = true, include = ["*"] } = rawOptions;
  if (!enable) return content;
  console.log(content);
  // Collect options
  const consoleMethod = ["console", "window.console"];
  let consoleAttr = [
    "assert",
    "clear",
    "context",
    "count",
    "countReset",
    "createTask",
    "debug",
    "dir",
    "dirxml",
    "error",
    "group",
    "groupCollapsed",
    "groupEnd",
    "info",
    "log",
    "memory",
    "profile",
    "profileEnd",
    "table",
    "time",
    "timeEnd",
    "timeLog",
    "timeStamp",
    "trace",
    "warn",
  ];
  if (Array.isArray(include) && !include.includes("*")) {
    consoleAttr = include.slice();
  }

  // Regular matching replacement
  const reg = new RegExp(
    "(" +
      consoleMethod.join("|") +
      ")\\.(" +
      consoleAttr.join("|") +
      ")\\(" +
      ".*" +
      "\\)" +
      ";*",
    "gi"
  );

  // Done
  content = content.replace(reg, () => {
    return "";
  });
  return content;
};

使用它

const path = require("path");
module.exports = {
  module:{
    rules:[
        test: /\.js$/,
        //依赖resolveLoader loader的规则按照modules来寻找
        loader: "cleanConsole",
        options:{
          enable:true, //开启
          include:['*'] //全部移除
        }
    ]
  },
  resolveLoader:{
    modules: ["node_modules", path.resolve(__dirname, "loaders")] //这里是我开发环境的目录
  }
  plugins: [new cleanConsoleWebpackPlugin()],
};
webpack loader
Theme Jasmine by Kent Liao