likes
comments
collection
share

compression-webpack-plugin实践

作者站长头像
站长
· 阅读数 17

一、用途“compression-webpack-plugin”插件能够通过压缩算法,将前端打包好的资源文件进一步压缩,生成指定的、体积更小的压缩文件,让浏览器能够更快的加载资源。

二、前端配置(vue.config.js)在打包过程中,可能会遇到“TypeError: Cannot read property 'tapPromise' of undefined”这样的错误,这是由于安装的“compression-webpack-plugin”版本太高导致的,通过安装低版本即可解决(cnpm i -D compression-webpack-plugin@6.1.0)。“filename”配置项必须明确指定,否则在vue cli创建的2.x和3.x项目中,生成的压缩文件位置存在差异。

const CompressionWebpackPlugin = require('compression-webpack-plugin');

module.exports = {
    productionSourceMap: false,
    configureWebpack: config => {
        config.plugins.push(new CompressionWebpackPlugin({
            filename: '[path][name].gz',
            test: /\.(js|css)$/i
        }));
    }
}

“npm run build”之后,可以发现生成了许多“.gz”格式的文件,这些文件就是压缩后的。compression-webpack-plugin实践

三、服务端配置生成压缩后的文件,不能直接使用,需要服务端配置才可以使用,而且发现打包生成的“dist/index.html”首页内,也没有直接引用这些“.gz”格式的文件。而实现的关键,其实就是让服务端向浏览器发送“Content-Encoding=gzip”这个响应头,并把对应的“.gz”格式文件发送给浏览器,让浏览器通过“gzip”编码格式来解析资源。

  1. nodejs实现将打包好的文件,丢至nodejs服务环境下,执行下列代码。

    const path = require('path');
    const fs = require('fs');
    const express = require('express');
    const app = express();
    
    app.use((request, response, next) => {
     const fullPath = path.join(__dirname, `${request.originalUrl}.gz`);     
     
     // 检测是否存在同名.gz压缩文件
     if (fs.existsSync(fullPath)) {
         // 存在就告诉浏览器用gzip编码格式来解析,并把对应的“.gz”格式文件发送给浏览器。
         response.setHeader('Content-Encoding', 'gzip')  
         response.sendFile(fullPath);
     } else {
         next()
     }
    })
    app.use(express.static('./'));
    
    app.listen(1055, _ => {
     console.log('1055服务器已经启动');
    });

    通过访问“http://localhost:1055/”,可以发现浏览器已经能够读取这些“.gz”格式的文件了,即使把打包的非压缩文件删除了也没问题。compression-webpack-plugin实践

  2. nginx实现(nginx.conf)在http模块内配置“gzip_static on”即可。

    http {
     gzip_static on;
    }

四、compression库这是一个nodejs的压缩中间件,提供的功能与“compression-webpack-plugin”差不多,所以如果是nodejs服务开发,并使用了这个库,那么前端也就没有必要再使用“compression-webpack-plugin”。


· 上述内容是通过查阅相关资料,以及个人的理解简要书写,更加详细的配置请参考官方文档,如有错误,随时欢迎指正。· 参考资料compression-webpack-plugin:https://www.npmjs.com/package...compression:https://www.npmjs.com/package...

转载自:https://segmentfault.com/a/1190000040268844
评论
请登录