ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

vue 使用 gzip 压缩 js 等静态资源

2021-10-11 13:32:24  阅读:200  来源: 互联网

标签:vue cdn js set gzip config 压缩


 

添加 js 压缩组件

npm install compression-webpack-plugin@1.1.12 --save-dev

 

配置 vue.config.js

// vue.config.js配置
const path = require('path')
// gzip压缩插件
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 代码打包之后取出console.log压缩代码
const TerserPlugin = require('terser-webpack-plugin')
// 图形化打包详情
const BundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

const cdn = {
  // 忽略打包的第三方库
  externals: {
    // vue: 'Vue',
    // vuex: 'Vuex',
    // 'vue-router': 'VueRouter',
    // axios: 'axios'
  },
  // 通过cdn方式使用
  js: [
    // 'https://cdn.bootcss.com/vue/2.6.11/vue.runtime.min.js',
    // 'https://cdn.bootcss.com/vue-router/3.1.2/vue-router.min.js',
    // 'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
    // 'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
    // 'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js',
    // 'https://cdn.bootcss.com/echarts/3.7.1/echarts.min.js'
  ],
  css: []
}

function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  // 是否触发eslint检查
  lintOnSave: false,
  publicPath: '/',
  // 打包文件的出口
  outputDir: 'dist',
  // 放置生成的css和js和img和fonts的目录
  // assetsDir: 'static',
  // 存放index.html模板的路径
  // indexPath: 'static/index.html',
  productionSourceMap: false,
  chainWebpack: config => {
    // 配置cdn引入
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })

    // 移除prefetch插件,避免加载多余的资源
    config.plugins.delete('prefetch')

    // 定义文件夹的路径
    // config.resolve.alias
    //   .set('@', resolve('src'))
    //   .set('assets', resolve('src/assets'))
    //   .set('components', resolve('src/components'))
    //   .set('router', resolve('src/router'))
    //   .set('store', resolve('src/store'))
    //   .set('views', resolve('src/views'))

    // 压缩图片
    const imagesRule = config.module.rule('images')
    imagesRule.uses.clear()
    imagesRule.use('file-loader')
      .loader('url-loader')
      .options({
        limit: 10240,
        fallback: {
          loader: 'file-loader',
          options: {
            outputPath: 'static/images'
          }
        }
      })

    // 压缩响应的app.json返回的代码压缩
    config.optimization.minimize(true)
  },
  // webpack的配置
  configureWebpack: config => {
    // 忽略打包配置
    config.externals = cdn.externals
    // 生产环境配置
    if (process.env.NODE_ENV === 'production') {
      // 代码压缩去除console.log
      config.plugins.push(
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'] // 移除console
            }
          }
        })
      )
    }

    // 开启gzip压缩
    config.plugins.push(
      new CompressionWebpackPlugin(
        {
          filename: info => {
            return `${info.path}.gz${info.query}`
          },
          algorithm: 'gzip',
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          test: new RegExp('\\.(' + ['js'].join('|') + ')$'
          ),
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        }
      )
    )

    // 展示打包图形化信息
    // config.plugins.push(
    //   new BundleAnalyzer()
    // )

    // 公共代码抽离
    config.optimization = {
      splitChunks: {
        cacheGroups: {
          vendor: {
            chunks: 'all',
            test: /node_modules/,
            name: 'vendor',
            minChunks: 1,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 100
          }
        }
      }
    }
  },
  css: {
    extract: true,
    sourceMap: false,
    loaderOptions: {
      // 定义全局scss无需引入即可使用
      sass: {
        prependData: `
          @import "@/assets/css/variable.scss";
          @import "@/assets/css/common.scss";
          @import "@/assets/css/mixin.scss";
        `
      },
      scss: {
        prependData: ` @import "~@/variables.scss"; `
      }
    }
  }
  // 需要gzip压缩的文件
  // devServer: {
  //   host: 'localhost',
  //   port: 8080, // 端口号
  //   open: false, // 配置自动启动浏览器
  //   before (app, server) {
  //     app.get(/.*.(js)$/, (req, res, next) => {
  //       req.url = req.url + '.gz'
  //       res.set('Content-Encoding', 'gzip')
  //       next()
  //     })
  //   }
  // }
}

 

配置 nginx

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;
        server_name *.demo.com;
gzip on; # 开启Gzip gzip_static on; # 开启静态文件压缩 gzip_min_length 1k; # 不压缩临界值,大于1K的才压缩 gzip_buffers 4 16k; gzip_http_version 1.1; gzip_comp_level 2; gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss; # 进行压缩的文件类型 gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_disable "MSIE [1-6]\."; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # rewrite index.html permanent; try_files $uri $uri/ /index.html; root /opt/web; index index.html index.htm index.nginx-debian.html; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } # pass PHP scripts to FastCGI server # #location ~ \.php$ { # include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): # fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # # With php-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }

 

标签:vue,cdn,js,set,gzip,config,压缩
来源: https://www.cnblogs.com/cnwcl/p/15392954.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有