学无先后,达者为师

网站首页 编程语言 正文

webpakc原理之开发一个清除console.log(xxx)的loader

作者:jieyucx 更新时间: 2023-07-26 编程语言

一、webpack中清除console的方法

当然想要清除console我们可以使用babel-loader结合babel-plugin-transform-remove-console插件来实现。

  1. 安装babel-loader和babel-plugin-transform-remove-console插件
npm install babel-loader babel-plugin-transform-remove-console -D
  1. 在webpack配置文件中配置loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: [['transform-remove-console', {exclude: ['error', 'warn']}]]
          }
        }
      }
    ]
  }
};

其中,babel-plugin-transform-remove-console插件中的exclude选项可以指定保留哪些日志级别的console语句。上面的示例中保留了errorwarn级别的console语句,其它级别的将被移除。如果不指定exclude选项,则会移除所有console语句。

二、自定义实现clean-console-loader

上面我们是借助babel插件实现的清除console,那么经过前面章节的铺垫,我们了解了loader的本质、执行顺序、以及分类还有常用的api,我们是否可以自己尝试写一个类似功能的loader呢?

下面我们就一起来实现一下吧

其实很简单就用正则匹配替换一下就行了,哈哈哈

  • clean-console.loader
module.exports = function (content) {
  // 清除文件内容中console.log(xxx)
  return content.replace(/console\.log\(.*\);?/g, "");
};

配置使用

  • webpack.config.js
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "./loaders/clean-log-loader",
      },
     ]
   }

这样就可以啦

  • main.js
    在这里插入图片描述
    我们在main.js中写两个console

打包看看效果

npm run dev

在这里插入图片描述
可以看到控制台干干净净什么都没有,说明我们自定义的清除console语句的loader生效啦。

原文链接:https://blog.csdn.net/jieyucx/article/details/131339662

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新