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

一、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生效啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jieyucx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值