webpack.config.js

  1. const{resolve} = require('path')
  2. const MiniCssExtractPlugin =require('mini-css-extract-plugin')
  3. const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
  4. const HtmlWebpackPlugin = require('html-webpack-plugin');
  5. //定义nodejs环境变量:决定使用browserslist的哪个环境
  6. process.env.NODE_ENV = 'production'
  7. //复用loader
  8. const commonCssLoader = [
  9. MiniCssExtractPlugin.loader,
  10. 'css-loader',
  11. {
  12. //还需要在package.json中定义browserslist
  13. loader:'postcss-loader',
  14. options:{
  15. ident:'postcss',
  16. plugins:()=>[
  17. require('postcss-preset-env')()
  18. ]
  19. }
  20. }
  21. ]
  22. module.exports = {
  23. entry:'./src/js/index.js',
  24. output:{
  25. filename:'js/built.js',
  26. path:resolve(__dirname,'build')
  27. },
  28. module:{
  29. rules:[
  30. {
  31. test:/\.css$/,
  32. use:[...commonCssLoader]
  33. },
  34. {
  35. test:/\.less$/,
  36. use:[ ...commonCssLoader,'less-loader']
  37. },
  38. /**
  39. * 正常来讲,一个文件只能被一个loader处理
  40. * 当一个文件要被多个loader处理,那么一定要指定loader执行的先后顺序:
  41. * 先执行eslint 再执行babel
  42. */
  43. {
  44. //在package.json中eslintConfig --> airbnb
  45. test:/\.js$/,
  46. exclude:/node_modules/,
  47. //优先执行
  48. enforce:'pre',
  49. loader:'eslint-loader',
  50. options:{
  51. fix:true
  52. }
  53. },
  54. {
  55. test:/\.js$/,
  56. exclude:/node_modules/,
  57. loader:'babel-loader',
  58. options:{
  59. preset:[
  60. [
  61. '@babel/preset-env',
  62. {
  63. //按需加载
  64. useBuiltIns:'usage',
  65. //指定core-js版本
  66. corejs:{
  67. version:3
  68. },
  69. targets:{
  70. chrome:'60',
  71. firefox:'60',
  72. ie:'9',
  73. safari:'10',
  74. edge:'17'
  75. }
  76. }
  77. ]
  78. ]
  79. }
  80. },
  81. {
  82. test:/\.(jpg|png|gif)/,
  83. loader:'url-loader',
  84. options:{
  85. limit:8*1024,
  86. name:'[hash:10].[ext]',
  87. outputPath:'../imgs',
  88. esModule:false
  89. }
  90. },
  91. {
  92. test:/\.html$/,
  93. loader:'html-loader'
  94. },
  95. {
  96. exclude:/\.(js|css|less|html|jpg|png|gif)/,
  97. loader:'file-loader',
  98. options:{
  99. outputPath:'media'
  100. }
  101. }
  102. ]
  103. },
  104. plugins:[
  105. new MiniCssExtractPlugin({
  106. filename:'css/built.css'
  107. }),
  108. new OptimizeCssAssetsWebpackPlugin(),
  109. new HtmlWebpackPlugin({
  110. template:'./src/index.html',
  111. minify:{
  112. collapseWhitespace:true,
  113. removeComments:true
  114. }
  115. })
  116. ],
  117. mode:'production'
  118. }

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. },
  13. "eslintConfig": {
  14. "extends": "airbnb-base"
  15. }