需下载插件:workbox-webpack-plugin

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. const WorkboxWebpackPlugin = require('workbox-webpack-plugin')
  6. /*
  7. PWA:渐进式网络开发应用程序(离线可访问)
  8. workbox --> workbox-webpack-plugin
  9. */
  10. //定义nodejs环境变量:决定使用browserslist的哪个环境
  11. process.env.NODE_ENV = 'production'
  12. //复用loader
  13. const commonCssLoader = [
  14. MiniCssExtractPlugin.loader,
  15. 'css-loader',
  16. {
  17. //还需要在package.json中定义browserslist
  18. loader: 'postcss-loader',
  19. options: {
  20. ident: 'postcss',
  21. plugins: () => [
  22. require('postcss-preset-env')()
  23. ],
  24. }
  25. }
  26. ]
  27. module.exports = {
  28. entry: './src/js/index.js',
  29. output: {
  30. filename: 'js/built.[contenthash:10].js',
  31. path: resolve(__dirname, 'build'),
  32. // publicPath: 'build'
  33. },
  34. module: {
  35. rules: [
  36. {
  37. //在package.json中eslintConfig --> airbnb
  38. test: /\.js$/,
  39. exclude: /node_modules/,
  40. //优先执行
  41. enforce: 'pre',
  42. loader: 'eslint-loader',
  43. options: {
  44. fix: true
  45. }
  46. },
  47. {
  48. //以下loader只会匹配一个
  49. //注意:不能有两个配置 处理同一个文件
  50. oneOf: [
  51. {
  52. test: /\.css$/,
  53. use: [...commonCssLoader],
  54. },
  55. {
  56. test: /\.less$/,
  57. use: [...commonCssLoader, 'less-loader']
  58. },
  59. /**
  60. * 正常来讲,一个文件只能被一个loader处理
  61. * 当一个文件要被多个loader处理,那么一定要指定loader执行的先后顺序:
  62. * 先执行eslint 再执行babel
  63. */
  64. {
  65. test: /\.js$/,
  66. exclude: /node_modules/,
  67. loader: 'babel-loader',
  68. options: {
  69. presets: [
  70. [
  71. '@babel/preset-env',
  72. {
  73. //按需加载
  74. useBuiltIns: 'usage',
  75. //指定core-js版本
  76. corejs: {
  77. version: 3
  78. },
  79. targets: {
  80. chrome: '60',
  81. firefox: '60',
  82. ie: '9',
  83. safari: '10',
  84. edge: '17'
  85. }
  86. }
  87. ],
  88. ],
  89. //开启babel缓存
  90. //第二次构建时,会读取之前的缓存
  91. cacheDirectory:true
  92. }
  93. },
  94. {
  95. test: /\.(jpg|png|gif)/,
  96. loader: 'url-loader',
  97. options: {
  98. limit: 8 * 1024,
  99. name: '[hash:10].[ext]',
  100. outputPath: '../imgs',
  101. esModule: false,
  102. }
  103. },
  104. {
  105. test: /\.html$/,
  106. loader: 'html-loader'
  107. },
  108. {
  109. exclude: /\.(js|css|less|html|jpg|png|gif)/,
  110. loader: 'file-loader',
  111. options: {
  112. outputPath: 'media',
  113. }
  114. }
  115. ]
  116. }
  117. ]
  118. },
  119. plugins: [
  120. new MiniCssExtractPlugin({
  121. filename: 'css/built.[contenthash:10].css'
  122. }),
  123. new OptimizeCssAssetsWebpackPlugin(),
  124. new HtmlWebpackPlugin({
  125. template: './src/index.html',
  126. minify: {
  127. collapseWhitespace: true,
  128. removeComments: true
  129. }
  130. }),
  131. new WorkboxWebpackPlugin.GenerateSW({
  132. /**
  133. * 1.帮助serviceworker快速启动
  134. * 2.删除旧的serviceworker
  135. *
  136. * 生成serviceworker的配置文件
  137. */
  138. clientsClaim:true,
  139. skipWaiting:true
  140. })
  141. ],
  142. mode: 'production',
  143. devtool:'source-map'
  144. }

index.js

  1. import { mul } from './test';
  2. import '../css/index.css';
  3. function sum(...args) {
  4. return args.reduce((p, c) => p + c, 0);
  5. }
  6. // eslint-disable-next-line
  7. console.log(mul(2, 3));
  8. // eslint-disable-next-line
  9. console.log(sum(1, 2, 3));
  10. /**
  11. * 1.eslint不认识window.navigator全局变量
  12. * 解决需要修改webpack.json中eslintConfig配置
  13. * "env":{
  14. "browser":true
  15. }
  16. 2.sw代码必须运行在服务器上
  17. --> nodejs
  18. -->
  19. npm i serve -g
  20. serve -s build 启动服务器,将build目录下所有资源作为静态资源暴露出去
  21. */
  22. // 注册serviceworker
  23. // 处理兼容性问题
  24. if ('serviceWorker' in navigator) {
  25. window.addEventListener('load', () => {
  26. navigator.serviceWorker.register('./service-worker.js')
  27. .then(() => {
  28. console.log('sw注册成功');
  29. })
  30. .catch(() => {
  31. console.log('sw注册失败');
  32. });
  33. });
  34. }

package.json

"eslintConfig": {
    "extends": "airbnb-base",
    "env":{
      "browser":true
    }
  },