提取css文件
需要引入插件:mini-css-extract-plugin
将style-loader 替换为MiniCssExtractPlugin.loader
const{resolve}= require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports={
entry:'./src/js/index.js',
output:{
filename:'js/built.js',
path:resolve(__dirname,'build')
},
module:{
rules:[
{
test:/\.css$/,
use:[
//创建style标签,将样式放入
// 'style-loader',
//这个loader取代style-loader。作用:提取js文件中的css成单独文件
MiniCssExtractPlugin.loader,
//将css文件整合到js文件中
'css-loader'
]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new MiniCssExtractPlugin({
//对输出文件的重命名
filename:'css/built.css'
})
],
mode:'development'
}
css兼容性处理
需引入插件postcss-loader和postcss-preset-env
修改postcss-loader默认配置
const{resolve}= require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
//设置nodejs环境变量
// process.env.NODE_ENV = 'development'
module.exports={
entry:'./src/js/index.js',
output:{
filename:'js/built.js',
path:resolve(__dirname,'build')
},
module:{
rules:[
{
test:/\.css$/,
use:[
MiniCssExtractPlugin.loader,
'css-loader',
/**
* css兼容性处理 :postcss --> postcss-loader postcss-preset-env
*
* 帮postcss找到packpage.json中browserslist里面的配置,通过配置加载指定的css兼容性样式
*
* "browserslist":{
"development":[
//开发环境 --> 设置环境变量:process.env.NODE_ENV=development
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production":[
//生产环境 :默认是生产环境
">0.01%",
"not dead",
"not op_mini all"
]
}
*/
//使用loader的默认配置
// 'postcss-loader'
//修改loader的配置
{
loader:'postcss-loader',
options:{
ident:'postcss',
plugins:()=>[
require('postcss-preset-env')()
]
}
}
]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new MiniCssExtractPlugin({
//对输出文件的重命名
filename:'css/built.css'
})
],
mode:'development'
}
修改package.json
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production": [
">0.01%",
"not dead" ,
"not op_mini all"
]
}
压缩css
需引入插件optimize-css-assets-webpack-plugin
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
plugins:[
//压缩css
new OptimizeCssAssetsWebpackPlugin()
],