Webpack根据webpack.config.js中的生产模式优化和压缩CSS和Javascript

时间:2020-04-04 12:04:37

标签: npm build webpack-4 npm-scripts npm-start

我在package.json中有以下NPM脚本:


select 
    resort.resortid,
    resort.resortname,
    review.comments ,
    case when starrating >= 4.5 and starrating < 5.0 then 'Excellent Resort'
         when starrating >= 4.0 and starrating < 4.4 then 'Very Good Resort'
         else 'Good Resort'
    end as rating
from resort 
    inner join review 
    on resort.resortid=review.resortid
;
  1. 如果我运行"scripts": { "start": "cross-env NODE_ENV=development webpack --mode development", "build": "cross-env NODE_ENV=production webpack --mode production" }, (<生产> 模式),我想添加npm run build(请参见下文)以压缩CSS并Uglify Javascript。我该如何实现?

    优化:{ 最小化器:[新的TerserJSPlugin({}),新的OptimizeCSSAssetsPlugin({})],
    },

  2. 如果我运行optimization,我想npm start的文件,除了watch以外,其他与生产模式相同。我正在构建一个Drupal站点,因此我也需要在开发中构建资产。

我的optimization现在看起来像这样:

webpack.config.js

如何构建它?

1 个答案:

答案 0 :(得分:0)

我通过如下调整webpack.config.js来解决它:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');

const config = {
  //Entry Point
  entry: {
    main: "./src/index.js",
    courses: "./src/courses.js",
    vendor: "./src/vendor.js"
  },
  //Output
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  //Watch
  watch: false,
  watchOptions: {
    ignored: ['node_modules']
  },
  //Loader
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { importLoaders: 1 } },
          'postcss-loader',
        ]
      },
      {
        //For fonts
        test: /\.(woff|woff2|ttf|otf|eot)$/,
        use: [
          {
            //using file-loader too
            loader: "file-loader",
            options: {
              outputPath: "fonts"
            }
          }
        ]
      }
    ]
  },
  //plugin
  plugins: [
    new MiniCssExtractPlugin({ filename: '[name].css' }),
    new CopyPlugin([
      { from: './src/assets/images', to: 'assets/images' },
      { from: './src/assets/icons', to: 'assets/icons' }
    ]),
  ],
};

module.exports = (env, argv) => {

  if (argv.mode === 'development') {
    //...
    config.mode = "development";
    config.watch = true;
  }

  if (argv.mode === 'production') {
    //...
    config.mode = "production";
    config.optimization = {
      splitChunks: {
        chunks: "all"
      },
      minimize: true,
      minimizer: [
        new OptimizeCssAssetsPlugin(),
        new TerserPlugin({
          cache: true
        })
      ]
    };
  }

  return config;
};

如果有人在上述方面有所改进,请告诉我。