日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

webpakc原理之開發(fā)一個(gè)清除console.log(xxx)的loader

作者:jieyucx 更新時(shí)間: 2023-07-26 編程語言

一、webpack中清除console的方法

當(dāng)然想要清除console我們可以使用babel-loader結(jié)合babel-plugin-transform-remove-console插件來實(shí)現(xiàn)。

  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選項(xiàng)可以指定保留哪些日志級(jí)別的console語句。上面的示例中保留了errorwarn級(jí)別的console語句,其它級(jí)別的將被移除。如果不指定exclude選項(xiàng),則會(huì)移除所有console語句。

二、自定義實(shí)現(xiàn)clean-console-loader

上面我們是借助babel插件實(shí)現(xiàn)的清除console,那么經(jīng)過前面章節(jié)的鋪墊,我們了解了loader的本質(zhì)、執(zhí)行順序、以及分類還有常用的api,我們是否可以自己嘗試寫一個(gè)類似功能的loader呢?

下面我們就一起來實(shí)現(xiàn)一下吧

其實(shí)很簡單就用正則匹配替換一下就行了,哈哈哈

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

配置使用

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

這樣就可以啦

  • main.js
    在這里插入圖片描述
    我們?cè)趍ain.js中寫兩個(gè)console

打包看看效果

npm run dev

在這里插入圖片描述
可以看到控制臺(tái)干干凈凈什么都沒有,說明我們自定義的清除console語句的loader生效啦。

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新