微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 Vuejs 与 webpack 结合使用的 PWA:如何缩小 Service Worker 代码?

如何解决将 Vuejs 与 webpack 结合使用的 PWA:如何缩小 Service Worker 代码?

我正在编写一个基于 Vuejs 的 PWA,并使用 webpack 作为打包器。我也在使用:

  • Terser 以缩小/修改代码
  • Google WorkBox 帮助服务工作者
  • 其他一些 webpack 插件,用于复制我的 Service Worker 需要的代码,并将其从 Service Worker 不支持import/export 语句中清除

现在我想缩小和修改 service worker 使用的代码,令我惊讶的是,认情况下它没有完成。有关如何进行的任何线索?我找不到将 Terser 应用到 service worker 代码的任何地方,而且我对 webpack 仍然很陌生...

我的vue.config.js

const WebpackAutoInject = require('webpack-auto-inject-version');
const {InjectManifest} = require('workBox-webpack-plugin');
const copyWebpackPlugin = require('copy-webpack-plugin');
const DumpVueEnvVarsWebpackPlugin = require('./src/DumpVueEnvVarsWebpackPlugin.js');
const TerserPlugin = require('terser-webpack-plugin');

function swfiletransform(filecontent) {
  return filecontent.toString()
  .replace(/^import .*?$/gm,'')
  .replace(/^export /gm,'')
  .replace(/\bmylist\./gm,'')
  .replace(/START_REMOVE_FROM_SW.*?END_REMOVE_FROM_SW/gms,'');
}

let config = {
  plugins: [
    // Version increment in package.json
    new WebpackAutoInject({
      components: {
        AutoIncreaseVersion: true,InjectAsComment: false
      },componentsOptions: {
        AutoIncreaseVersion: {
          runInWatchMode: false // it will increase version with every single build!
        }
      }
    }),// To have environment variables available in service worker
    new DumpVueEnvVarsWebpackPlugin({ filename: 'my-env-vars.js' }),// WorkBox service worker
    new InjectManifest({ swSrc: './public/service-worker.js' }),// For the service worker,copy files and remove import/export statement which are not supported yet by SW (yes,it is a hack)
    new copyWebpackPlugin ({
      patterns: [
        { from: 'src/js/mylist.js',to: '',transform: content => swfiletransform(content),},{ from: 'src/js/mydico.js',transform: content => swfiletransform(content) },{ from: 'src/js/textparser.js',{ from: 'src/js/compressor.js',transform: content => swfiletransform(content) }
    ]})
  ],}
// If in prod,optimize
if(process.env.NODE_ENV === 'production')
  config.optimization = {
    minimize: true,minimizer: [
      // https://github.com/terser/terser#minify-options
      new TerserPlugin({
        terserOptions: {
          compress: {
            pure_funcs: [ process.env.KEEP_CONSOLE ? '' : 'console.log' ],keep_infinity: true
          },mangle: {
            eval: true,toplevel: true
          },warnings: true,output: {
            comments: false
          },})
    ],}

// https://cli.vuejs.org/config/#vue-config-js
module.exports = { 
  configureWebpack: config,productionSourceMap: process.env.NODE_ENV != 'production'
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。