1.打包CSS文件css
npm安裝:html
npm install --save-dev style-loader css-loader
webpack.config.js下配置node
module.exports = { module:{ rules :[ { test : /\.css$/, use:['style-loader','css-loader'] } ] } }
在入口文件引入css文件進行測試webpack
import css from './css/xxx.css';
2.對css進行抽離web
npm安裝npm
npm install --save-dev extract-text-webpack-plugin
webpack.config.js下配置sass
//對css進行抽離 const extractTextWebpackPlugin = require('extract-text-webpack-plugin'); module.exports = { module:{ rules :[ { test : /\.css$/, use:extractTextWebpackPlugin.extract({ fallback: "style-loader", use:[ 'css-loader' ] }) } ] } ,plugins:[ new extractTextWebpackPlugin('./css/[name].css') //將css抽離至出口文件目錄:css/[name].css ] }
3.自動添加後綴less
npm安裝post
npm install --save-dev postcss-loader autoprefixer
根目錄下建立postcss.config.js,並配置測試
module.exports = { plugins: [ require('autoprefixer') ] }
webpack.config.js下配置
//對css進行抽離 const extractTextWebpackPlugin = require('extract-text-webpack-plugin'); module.exports = { module:{ rules :[ { test : /\.css$/, use:extractTextWebpackPlugin.extract({ fallback: "style-loader", use:[ 'css-loader', 'postcss-loader' ] }) } ] } ,plugins:[ new extractTextWebpackPlugin('./css/[name].css') //將css抽離至出口文件目錄:css/[name].css ] }
4.消除未使用的css
注:使用這個插件必須配合extract-text-webpack-plugin插件
npm安裝
npm install --save-dev purifycss-webpack purify-css
webpack.config.js下配置
const glob = require('glob'); //同步檢查html模板 const purfyCssPlugin = require('purifycss-webpack'); module.exports = { plugins:[ new purfyCssPlugin({ paths:glob.sync(path.join(__dirname,'src/*.html')) }) ], }
5.打包和分離LESS
npm安裝
//安裝Less的服務 npm install --save-dev less //安裝Less-loader用來打包使用 npm install --save-dev less-loader
編寫一個less文件:style.less
@body-color :#000; body{ background-color:@body-color; }
引入到入口文件entery.js中
import less from './css/style.less'
webpack.config.js下配置
//對css進行抽離 const extractTextWebpackPlugin = require('extract-text-webpack-plugin');
module.exports = { module:{ rules :[ { test: /\.less$/, use: extractTextPlugin.extract({ fallback: "style-loader", use: [{ loader: "css-loader" }, { loader: "less-loader" }] }) } ] } ,plugins:[ new extractTextWebpackPlugin('./css/[name].css') //將css抽離至出口文件目錄:css/[name].css ] }
6.打包和分離SCSS
npm安裝
//sass-loader依賴於node-sass,要先安裝node-sass npm install --save-dev node-sass //安裝Less的服務 npm install --save-dev sass-loader
編寫一個scss文件:style.scss
$body-color :#000; body{ background-color:$body-color; }
引入到入口文件entery.js中
import scss from './css/style.scss'
webpack.config.js下配置
//對css進行抽離 const extractTextWebpackPlugin = require('extract-text-webpack-plugin'); module.exports = { module:{ rules :[ { test: /\.less$/, use: extractTextPlugin.extract({ fallback: "style-loader", use: [{ loader: "css-loader" }, { loader: "sass-loader" }] }) } ] } ,plugins:[ new extractTextWebpackPlugin('./css/[name].css') //將css抽離至出口文件目錄:css/[name].css ] }