小白学 Webpack之HTML/CSS 压缩代码

webpack 实现压缩 css

默认情况下,webpack 在生成环境下会自动压缩js,html,所以我们只需要处理好css压缩即可。
同理先安装下依赖包
package.json

{
  "name": "webpack3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "autoprefixer": "^8.0.1",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.3.0",
    "eslint": "^7.11.0",
    "eslint-loader": "^4.0.2",
    "eslint-webpack-plugin": "^2.1.0",
    "file-loader": "^6.1.1",
    "html-loader": "^1.3.2",
    "html-webpack-plugin": "^4.5.0",
    "less": "^3.12.2",
    "less-loader": "^7.0.2",
    "mini-css-extract-plugin": "^1.0.0",
    "postcss-loader": "^4.0.4",
    "postcss-preset-env": "^6.7.0",
    "sass": "^1.27.0",
    "sass-loader": "^10.0.3",
    "scss": "^0.2.4",
    "scss-loader": "0.0.1",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.0.0",
    "webpack-cli": "^4.0.0",
    "webpack-dev-server": "^3.11.0"
  }
}

css 压缩插件 optimize-css-assets-webpack-plugin

npm i -D optimize-css-assets-webpack-plugin

配置插件

var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  module: {
   ...
  plugins: [

    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorPluginOptions: {
        preset: ['default', { discardComments: { removeAll: true } }],
      },
      canPrint: true
    })
  ]
    ...
};

部署文件来测试一下

|-- postcss.config.js
|-- src
|   |-- css
|   |   `-- base.css
|   |-- index.html
|   |-- js
|   |   `-- index.js
|   `-- less
|       `-- base.less
`-- webpack.config.js

来设置下引入css
index.js

require('../css/base.css');
require('../less/base.less');

base.css

h1{
    font-size: 18px;
    color: #000;
    text-align: center;
    font-weight: bold;
}
h2{
    font-size:16px;
    color: #0044dd;
}

base.less

p{
    font-size: 14px;
    color: #787878;
}
span{
    margin-right: 10px;
    margin-left: 5px;
}
i{
    font-style: normal;

}

webpack ,生成压缩了
描述

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。