1.打包压缩css文件
css-loader: 加载解析文件,如遇到@import会将相应的样式文件引入(如没有css-loader则不会引入该文件)
style-loader:将解析的css放style标签,插入head标签里
(css样式打包到main.js文件里)
实例:
/* demo.css*/
body{
background: #ccc;
}
div{
height: 200px;
width: 200px;
background: tomato;
}
p{
font-size: 50px;
font-weight: 800;
}
a{
color: green;
}
//index.js
import './demo.css';
//webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
}
}
<!-- index.html -->
<div></div>
<script src="./dist/main.js"></script>
2.单独抽离出css文件
mini-css-extract-plugin:将css抽离到单独的文件中
安装 npm install mini-css-extract-plugin --save-dev
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader,'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin()
]
}
3.css-tree-shaking
purifycss-webpack:移除没有使用到css样式
安装 npm install purifycss-webpack purifycss --save-dev
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const path = require('path');
const glob = require('glob')
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader,'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
}),
new PurifyCSSPlugin({
paths: glob.sync(path.join(__dirname, './*.html'))
})
]
}
另:若在js文件中操作dom元素,则需另外配置,如
安装glob-all
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const path = require('path');
const glob = require('glob-all');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
}),
new PurifyCSSPlugin({
paths:
glob.sync([
path.join(__dirname, './*.html'),
path.join(__dirname, './src/*.js')])
})
]
}