webpack打包后發現有一部分代碼還攜帶注釋,如何解決?/webpack打包刪除注釋以及console.log--快快點進來看一看吧~~


1.自己配置了一個webpack,打包后發現里邊部分代碼還存在注釋,頓感不妙

廢話不多說 解決如下:

npm install terser-webpack-plugin --save-dev

然后在webpack.config.js文件中進行配置

const TerserWebpackPlugin = require('terser-webpack-plugin');
// 實例化TerserWebpackPlugin對象
const terserPlugin = new TerserWebpackPlugin({
  parallel: 4,
  extractComments: true,
  terserOptions: {
    compress: {
      warnings: false,
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log'] //移除console
    }
  }
});

module.exports = {
	optimization: {
    	minimizer: [
      	// 只有打包環境為production時才能生效
      	terserPlugin
    ],
  },
}

開開心心運行 npm run build

啪啪啪打臉,報錯了,報錯信息如下:

const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation); 
TypeError: Cannot read property 'javascript' of undefined

解決問題:由於terser-webpack-plugin@5與webpack @ 4不兼容,所以運行npm uninstall terser-webpack-plugin

然后運行 試一把~~~~

 npm install terser-webpack-plugin@4.2.3 --save-dev

打包成功了 為啥還有注釋????

啪啪啪又打臉了????!!!!

好了,最終發現原因,因為生產環境配置了devtool: 'cheap-module-eval-source-map'導致代碼被轉成了字符串,所以無法刪除注釋

最終解決方案如下: 打包時候注釋掉 webpack.config.js里的

devtool: 'cheap-module-eval-source-map', //開發環境下使用

保存代碼 ,重新打包~ 完美~~

完整版的webpack.config.js配置,打包時候記得注釋掉那個map插件,然后publicPath根據需要設置,其實注釋掉不要也可以的

// 如果有額外的.babelrc配置的話就可以使用這段代碼1
// module.exports = {
//   module: {
//     rules: [
//       {
//         test:/\.jsx?$/,
//         use: ['babel-loader'],
//         exclude:/node_modules/  //排除 node_modules目錄
//       }
//     ]
//   }
// }
// 如果有額外的.babelrc配置的話就可以使用這段代碼2
// 在webpack中配置 babel,如果沒有額外的.babelrc配置的話就可以使用這段代碼1
//webpack.config.js
// 首先引入插件1
// 導入terser-webpack-plugin-->減少js體積(其中刪除js的console.log和注釋)
const TerserWebpackPlugin = require('terser-webpack-plugin')
// 實例化TerserWebpackPlugin對象
const terserPlugin = new TerserWebpackPlugin({
  parallel: 4,
  extractComments: true,
  terserOptions: {
    compress: {
      warnings: false,
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log'], //移除console
    },
  },
})
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isDev = process.env.NODE_ENV.trim() === 'development' //html-webpack-plugin 的 config 的妙用4-1
const { CleanWebpackPlugin } = require('clean-webpack-plugin') //清理dist目錄的插件
const path = require('path') //設置出口使用
const config = require('./public/config')[isDev ? 'dev' : 'build'] //html-webpack-plugin 的 config 的妙用4-2
module.exports = {
  entry: './src/index.js', //webpack的默認配置,也可以寫一個數組
  output: {
    path: path.resolve(__dirname, 'dist'), //必須是絕對路徑
    // filename: 'bundle.js',
    // filename: 'bundle.[hash].js',
    filename: 'bundle.[hash:6].js', //考慮到CDN緩存的問題,我們一般會給文件名加上 hash
    // publicPath: '/' // 打包上線之前要改一下這個哦TODU-LIST
  },
  mode: isDev ? 'development' : 'production', //html-webpack-plugin 的 config 的妙用4-3
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: [
              [
                '@babel/plugin-transform-runtime',
                {
                  corejs: 3,
                },
              ],
            ],
          },
        },
        exclude: /node_modules/,
      },
      {
        //看清楚啦  這裡有四個loaderloader 的執行順序是從右向左執行的,也就是后面的 loader 先執行,上面 loader 的執行順序為: less-loader ---> postcss-loader ---> css-loader ---> style-loader
        test: /\.(le|c)ss$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: function () {
                return [
                  require('autoprefixer')({
                    overrideBrowserslist: ['>0.25%', 'not dead'],
                  }),
                ]
              },
            },
          },
          'less-loader',
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(png|jpg|gif|jpeg|webp|svg|eot|gltf|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'url-loader',
            // options: {
            //     limit: 10240, //10K
            //     esModule: false
            // }
            // ,
            // 使用上面的那一段運行後會把圖片名字改為MD5哈希值,使用下面的會保留原有名稱加上六位哈希值
            options: {
              limit: 10240, //10K
              // publicPath: './src/',
              esModule: false,
              name: '[name]_[hash:0].[ext]',
              outputPath: 'assets', //這個可以將打包後的資源放到指定的文件夾下
            },
          },
        ],
        exclude: /node_modules/,
      },
      // {
      //   test: /\.html$/,
      //   use: 'html-withimg-loader'
      // },
    ],
  },
  optimization: {
    minimizer: [
      // 只有打包環境為production時才能生效
      terserPlugin,
    ],
  },
  plugins: [
    // 數組,放著所有的webpack插件
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      config: config.template, //html-webpack-plugin 的 config 的妙用4-4
      minify: {
        removeAttributeQuotes: false, //是否刪除屬性的雙引號
        collapseWhitespace: false, //是否折疊空白
      },
      hash: true, //是否加上hash,默認是false
    }),
    new CleanWebpackPlugin(), //清理dist目錄插件,不需要傳參數,它自己可以找到outPath
    // new CleanWebpackPlugin({cleanOnceBeforeBuildPatterns:['**/*','!dll','!dll/**']}) //如果你有需要不刪除dll目錄下的文件的話可以這樣子寫
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'src/assets/',
          to: 'assets/',
        },
      ],
    }),
  ],
  devServer: {
    port: '8080', //默認是8080
    quiet: false, //默認不啟動
    inline: true, // 默認開啟inline 模式,如果設置為false, 開啟 iframe模式
    stats: 'errors-only', //終端僅僅打印 error
    overlay: false, //默認不啟用
    clientLogLevel: 'silent', //日誌等級
    compress: true, //是否啟用gzip壓縮
  },
  devtool: 'cheap-module-eval-source-map', //開發環境下使用 打包上線之前要改一下這個哦TODU-LIST
}

// 在webpack中配置 babel,如果沒有額外的.babelrc配置的話就可以使用這段代碼2



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM