首页 > 解决方案 > 使用 webpack 为 Angular 6 项目缩小多个 css 文件

问题描述

Angular 6 压缩了 CSS 文件,但没有缩小它。我需要缩小 CSS 文件。

目前我正在使用这些命令进行生产构建。

包.json

"build": "run-s build:client build:aot build:server",
"build:client": "ng build --prod --build-optimizer && ng run elgrocer:server",
"build:aot": "ng build --aot --prod --build-optimizer --output-hashing=all",
"build:server": "webpack -p"

webpack.config.js

    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].js'
      },
      module: {
        rules: [
          { test: /\.ts$/, loader: 'ts-loader' }
        ]
      },
      optimization: {
        minimizer: [
          new UglifyJsPlugin()
        ]
      },
      plugins: [
        new CompressionPlugin({
          algorithm: 'gzip'
        })
      ]

目前它像这样在 index.html 文件中添加 css 样式。

<style ng-transition="app">.sign-in[_ngcontent-sc6] {
    font-size: 15px;
    padding: 8px 16px;
    border-radius: 100px;
}

.sign-up[_ngcontent-sc6] {
    font-size: 15px;
    padding: 6px 14px;
    border-radius: 100px;
    border: 2px solid var(--Primary-Brand-1)!important;
    color: var(--Primary-Brand-1);
}

.sign-in[_ngcontent-sc6] {
    background: var(--Primary-Brand-1);
}

.top-nav[_ngcontent-sc6]   li[_ngcontent-sc6] {
    list-style: none;
    display: inline-block;
    margin-left: 10px
}</style>

期望的结果

<style ng-transition="app">.sign-in[_ngcontent-sc6]{font-size:15px;padding:8px 16px;border-radius:100px;}.sign-up[_ngcontent-sc6]{font-size:15px;padding:6px 14px;border-radius:100px;border:2px solid var(--Primary-Brand-1)!important;color:var(--Primary-Brand-1);}.sign-in[_ngcontent-sc6]{background:var(--Primary-Brand-1);}.top-nav[_ngcontent-sc6]li[_ngcontent-sc6]{list-style:none;display:inline-block;margin-left:10px}</style>

标签: angularwebpackangular6minifywebpack-3

解决方案


您可以使用CssMinimizerWebpackPlugin。首先安装它:

$ npm install css-minimizer-webpack-plugin --save-dev

然后将其添加到您的配置中:

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

...

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  },
  optimization: {
    minimize: true,
    minimizer: [
      new UglifyJsPlugin(),
      new CssMinimizerPlugin()
    ]
  },
  plugins: [
    new CompressionPlugin({
      algorithm: 'gzip'
    })
  ]

从您的编辑中编辑

也许您有这种行为是因为您没有在单独的文件中提取 css,因此您可以使用使用HtmlWebpackPlugin来完成这项工作:

npm install --save-dev html-webpack-plugin

在您的配置中添加插件:

var HtmlWebpackPlugin = require('html-webpack-plugin');


  plugins: [
    new HtmlWebpackPlugin(),
    new CompressionPlugin({
      algorithm: 'gzip'
    })
  ]

推荐阅读