6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

webpackのproductionモードで自動minyfyされなかった

Last updated at Posted at 2020-06-09

webpack4のproductionモードのとき、
コードが自動でminifyされると思ってましたが、場合によってはそうでもないみたいです:rolling_eyes:

はまったパターン

CSSをminifyするためOptimizeCSSAssetsPluginを設定

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = {
  // メインとなるJavaScriptファイル(エントリーポイント)
  entry: ["./src/js/index.js"],
  output: {
    filename: "js/main.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({filename: 'style/[name].css'}),
  ],
  optimization: {
    minimizer: [new OptimizeCSSAssetsPlugin({})],
  },
}

↓build
cssのminifyはされたけどjsのminifyがされない…

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
:
:

原因

調べてみると、optimization.minimizerを設定すると既存の設定が全て上書きされるので、minifyの設定は自分でしなきゃいけないようです。

If you decide to try another minification plugin, just make sure your new choice also drops dead code as described in the tree shaking guide and provide it as the optimization.minimizer.

公式

解決

公式で紹介されてるterser-webpack-pluginを使用しました。

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

const TerserPlugin = require("terser-webpack-plugin");
:
optimization: {
 minimizer: [
   new TerserPlugin(),
   new OptimizeCSSAssetsPlugin() // CSS の minify を行う
 ]
},

↓build

!function(e){var t={};function n(i){if(t[i])return t[i].exports;var o=t[i]={i:i,l:!1,exports:{}};..

無事minifyされました。

公式に思いっきり書いてたのに…
反省と共に投稿です:skull:

webpackがあればgulpとかタスクランナーいらないぜ!ってのをネットで良く聞くのですが、
書いてみて結構長くなって読み辛くなってしまったと感じます。

webpackとタスクランナー併用で使って、わかりやすいの欲しいなーと思ったので、次はそれ作ってみます:eyes:

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?