提取css文件

需要引入插件:mini-css-extract-plugin

将style-loader 替换为MiniCssExtractPlugin.loader

  1. const{resolve}= require('path')
  2. const HtmlWebpackPlugin = require("html-webpack-plugin");
  3. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  4. module.exports={
  5. entry:'./src/js/index.js',
  6. output:{
  7. filename:'js/built.js',
  8. path:resolve(__dirname,'build')
  9. },
  10. module:{
  11. rules:[
  12. {
  13. test:/\.css$/,
  14. use:[
  15. //创建style标签,将样式放入
  16. // 'style-loader',
  17. //这个loader取代style-loader。作用:提取js文件中的css成单独文件
  18. MiniCssExtractPlugin.loader,
  19. //将css文件整合到js文件中
  20. 'css-loader'
  21. ]
  22. }
  23. ]
  24. },
  25. plugins:[
  26. new HtmlWebpackPlugin({
  27. template:'./src/index.html'
  28. }),
  29. new MiniCssExtractPlugin({
  30. //对输出文件的重命名
  31. filename:'css/built.css'
  32. })
  33. ],
  34. mode:'development'
  35. }

css兼容性处理

需引入插件postcss-loader和postcss-preset-env

修改postcss-loader默认配置

  1. const{resolve}= require('path')
  2. const HtmlWebpackPlugin = require("html-webpack-plugin");
  3. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  4. //设置nodejs环境变量
  5. // process.env.NODE_ENV = 'development'
  6. module.exports={
  7. entry:'./src/js/index.js',
  8. output:{
  9. filename:'js/built.js',
  10. path:resolve(__dirname,'build')
  11. },
  12. module:{
  13. rules:[
  14. {
  15. test:/\.css$/,
  16. use:[
  17. MiniCssExtractPlugin.loader,
  18. 'css-loader',
  19. /**
  20. * css兼容性处理 :postcss --> postcss-loader postcss-preset-env
  21. *
  22. * 帮postcss找到packpage.json中browserslist里面的配置,通过配置加载指定的css兼容性样式
  23. *
  24. * "browserslist":{
  25. "development":[
  26. //开发环境 --> 设置环境变量:process.env.NODE_ENV=development
  27. "last 1 chrome version",
  28. "last 1 firefox version",
  29. "last 1 safari version"
  30. ],
  31. "production":[
  32. //生产环境 :默认是生产环境
  33. ">0.01%",
  34. "not dead",
  35. "not op_mini all"
  36. ]
  37. }
  38. */
  39. //使用loader的默认配置
  40. // 'postcss-loader'
  41. //修改loader的配置
  42. {
  43. loader:'postcss-loader',
  44. options:{
  45. ident:'postcss',
  46. plugins:()=>[
  47. require('postcss-preset-env')()
  48. ]
  49. }
  50. }
  51. ]
  52. }
  53. ]
  54. },
  55. plugins:[
  56. new HtmlWebpackPlugin({
  57. template:'./src/index.html'
  58. }),
  59. new MiniCssExtractPlugin({
  60. //对输出文件的重命名
  61. filename:'css/built.css'
  62. })
  63. ],
  64. mode:'development'
  65. }

修改package.json

  1. "browserslist": {
  2. "development": [
  3. "last 1 chrome version",
  4. "last 1 firefox version",
  5. "last 1 safari version"
  6. ],
  7. "production": [
  8. ">0.01%",
  9. "not dead" ,
  10. "not op_mini all"
  11. ]
  12. }

压缩css

需引入插件optimize-css-assets-webpack-plugin

  1. const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
  2. plugins:[
  3. //压缩css
  4. new OptimizeCssAssetsWebpackPlugin()
  5. ],