webpack4.0关闭开发环境的代码压缩UglifyJsPlugin

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanglong_web/article/details/79618055

  最近项目使用的是webpack4.1.1,在使用之前是没有细看更新后版本的文档的,在使用过程中才发现还是有很大的变化。其中一个就是关于UglifyJsPlugin的配置问题。
  开发环境是不需要去压缩代码,主要是因为太耗性能了,每修改一个地方就要花几秒去等待页面渲染,说实话这非常浪费开发时间,解决办法就是配置不同的环境变量去在开发环境的时候不要这个UglifyJsPlugin插件,为此,webpack4又增加了新的Mode,且默认值是production,而且更新后的webpack默认是有UglifyJsPlugin这个配置的,也就是说在不设置任何环境变量的情况下,始终会有压缩代码的行为出现,导致编译极其耗时,那我的解决办法就是在package.json文件启动时设置环境变量:

  "scripts": {
    "dev": "rm -rf ./dist && webpack-dev-server --inline --progress --mode development --config webpack.config.js",
    "build": "rm -rf ./dist && webpack"
  },

  同样的也可以在打包的时候也设置环境变量,这样就不会在开发环境频繁的去压缩代码,节省了很多没必要的等待时间,而且频繁压缩也会导致热更新HotModuleReplacementPlugin根本毫无作用。下面是webpack的配置:

const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const webpack = require('webpack')
const path = require('path')

const config = {
  // mode: 'development',
  entry: {
    vendor: [
      'jquery',
      'echarts/lib/echarts',
      'echarts/lib/chart/pie',
      'echarts/lib/chart/bar',
      'echarts/lib/chart/line',      
      'echarts/lib/component/tooltip',
      'echarts/lib/component/title'
    ],
    beauty: path.resolve(__dirname, 'src/js/beauty.js'),
    shadow: path.resolve(__dirname, 'src/js/shadow.js')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        loader: 'html-loader',
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
      },
      {
        test: /\.less$/,
        use: [{
          loader: 'style-loader',
        }, {
          loader: 'css-loader',
        }, {
          loader: 'less-loader',
        }],
      },
      {
        test: /\.json$/,
        loader: 'file-loader',
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: [
          'url-loader?limit=10000',
          'img-loader',
        ],
      },
      {
        test: /\.(webm|mp4)$/,
        loader: 'file-loader',
      },
    ],
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      _: 'lodash'
    }),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, 'src/beauty.html'),
      chunks: ['vendor', 'beauty'],
    }),
    new HtmlWebpackPlugin({
      filename: 'shadow.html',
      template: path.resolve(__dirname, 'src/shadow.html'),
      chunks: ['vendor', 'shadow'],
    })
  ],
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

module.exports = config

  虽然只是小小的改动,但是提高了开发的效率,也是有点小强迫症,看着每次编译都要等个3秒真的是太难受了,不过webpack4.0肯定还是有很多的变化和更新等着去我们去探(踩)索(坑),不过踩的越多会的也就越多~

猜你喜欢

转载自blog.csdn.net/zhanglong_web/article/details/79618055
今日推荐