处理sass
npm i -D node-sass sass-loader
安装sass-loader
和node-sass
webpack.config.js
文件中module.exports
对象中module
模块rules
增加规则module:{ rules:[ // 用style-loader和css-loader处理css文件 { test:/\.(c|sc|sa)ss$/, use:[ 'style-loader', 'css-loader', "sass-loader" ] } ] }
npx webpack命令更改,可以在package.json文件中scripts脚本中增加"bulid":"npx webpack",然后运行npm run build 就可以打包了
css
文件提取为单独的文件
- 安装
mini-css-extract-plugin
npm install --save-dev mini-css-extract-plugin
webpack.config.js
文件中添加// 添加 const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // module.exports添加 module.exports = { module:{ rules:[ // 用style-loader和css-loader处理css文件 { test:/\.(c|sc|sa)ss$/, use:[ MiniCssExtractPlugin.loader, { loader:'css-loader', options:{ sourceMap:true } }, { loader: 'postcss-loader', options: { ident: 'postcss', sourceMap:true, plugins: [ require('autoprefixer')({browsers:['> 0.15% in CN']}) ] } }, { loader:"sass-loader", options:{ sourceMap:true } } ] }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', // 增加hash值 // filename: '[name].[hash].css', chunkFilename: '[id].css', ignoreOrder: false, }) ], }
css
和js
的压缩
- 安装
optimize-css-assets-webpack-plugin
npm install --save-dev optimize-css-assets-webpack-plugin
webpack.config.js
文件增加var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); module.exports = { plugins: [ new OptimizeCssAssetsPlugin() ], }
图片处理
- 安装
file-loader
npm install file-loader --save-dev
webpack.config.js
文件中module.exports = { module: { rules: [ { test: /\.(png|jpe?g|gif)$/i, use: [ { loader: 'file-loader', }, ], }, ], }, };
图片优化(压缩)
- 安装
image-webpack-loader
npm install image-webpack-loader --save-dev
webpack.config.js
文件中module.exports = { module: { rules: [{ test: /\.(gif|png|jpe?g|svg)$/i, use: [ 'file-loader', { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true, quality: 65 }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: { quality: [0.65, 0.90], speed: 4 }, gifsicle: { interlaced: false, }, // the webp option will enable WEBP webp: { quality: 75 } } }, ], }] } }
图片base64
优化
- 安装
url-loader
npm install url-loader --save-dev
webpack.config.js
文件中module.exports = { module: { rules: [ { test: /\.(png|jpg|gif)$/i, use: [ // file-loader // url-loader可以替换file-loader { loader: 'url-loader', options: { limit: 8192, }, }, { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true, quality: 65, }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: { quality: [0.65, 0.90], speed: 4, }, gifsicle: { interlaced: false, }, // the webp option will enable WEBP webp: { quality: 75, }, }, }, ], }, ], }, };