Vue released encountered during the pit, and webpack packaging optimization

Foreword

  • During this time, I own a vue on the screen to deploy their own servers found running slowly amazing, although the server is slag (himself no money, can only rent the worst servers, mainly used for their own learning ), but this developed website simply can not be used, so the inspection of various materials and website, step by step to optimize the code package. This article is my tuning process recorded.
  • Basic framework of the project is achieved by TypeScript official website. A variety of basic template framework
  • The project constitutes vue + ant-design + mysql + TypeScript
  • vue project address
  • Finally, with regard to how to achieve inside vue loaded on demand, please consult the relevant information on their own. And, webpack the basics of this article describes do not, I can refer to the github  study notes
  • [Original Address] ( http://shenxf.top/2019/05/16/20190516-vueSpeedUp/ )

Tuning process

  1. Disable webpack of devtools
  • Pack out of the js file is very large, each js file has reached the 3 ~ 4Mbs, this volume is the bandwidth for my services simply can not afford the burden. The screen will open the card.
  • The reason is because webpack which enabled sourceMap, for debugging purposes. But this is completely useless in later releases.
  • webpack configuration, which has this sentence, this sentence commented. 3 ~ 4Mbs original documents into a 1Mbs file. Compressed more than 3 times.
  • // Enable sourceMap
    devtool: '#source-map'

     

  1. Detached css styles, etc.
  • Although this effect is not obvious for improvement, but good classification is very helpful to discover the nature of the problem. In addition, css style after separation to compress themselves.

    Package ************************* // ************* webpack need to be introduced
    // pulled css styles
    let MiniCssExtractPlugin = require('mini-css-extract-plugin');
    // used to compress separated css styles
    let OptimizeCss =  require('optimize-css-assets-webpack-plugin');
    // used to compress js
    let UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    
    // ************* webpack configuration section *************************
    module.exports = {
        optimization: { // OPTIMIZES
            minimizer: [ new OptimizeCss (), // css compression new UglifyJsPlugin ({// compression js cache: true, // whether to use the cache parallel: true, // concurrency package sourceMap: false, // es6 -> will be used when converting es5
    }),],} // // intermediate portion omitted pulled css style plugins: [new new MiniCssExtractPlugin ({filename: 'css / [name] .css', // pulled out style name }),],}
     
  • After detached, now the size of the project file is generated. JS file size
    JS file size

  1. Enable dependency visualization tools
  • After completion of the above work, caught up in a loss, the website is still very slow, but also do not know how to tune in to read a lot of information on the site after the discovery of a dependency visualization tool, which for me is a major breakthrough

    // dependency visualization
    Package ************************* // ************* webpack need to be introduced
    const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
    
    // ************* webpack configuration section *************************
    module.exports = {
    
        // start dependency visualization windows, bind port 8919
        plugins: [
            new BundleAnalyzerPlugin({ analyzerPort: 8919 }),
        ],
    }
     
  • Recompile later renderings dependency graph JS files
    JS file dependency graph

  • Through this renderings can clearly see what js file which contains dependent, I came to be optimized through this trail.

  1. Detached common part
  • In order to facilitate my investigation, I rely on the common parts are pulled out. And this function is webpack4 comes, if it is before or earlier webpack, requires the introduction of third-party components CommonsChunkPluginnot described here.

    module.exports = {
        optimization: {
            // packed public documents
            splitChunks: {
                Cache groups: {
                    vendor: {
                        //node_modules内的依赖库
                        chunks: 'all',
                        test: /[\\/](node_modules)[\\/]/, // 文件路径里面带有node_modules 都抽离出来做共通
                        name: 'vendor',
                        minChunks: 1, //被不同entry引用次数(import),1次的话没必要提取
                        maxInitialRequests: 5,
                        minSize: 0, priority: 100, // enforce: true?  }, common: { // ‘src/js’ 下的js文件 chunks: 'all', test: /[\\/]src[\\/]js[\\/]/, //也可以值文件/[\\/]src[\\/]js[\\/].*\.js/, name: 'common', //生成文件名,依据output规则 minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 1, }, }, }, runtimeChunk: { name: 'manifest', }, } } 
  • 一开始我对于这个属性的名字难以理解,以至于没有效果,看了下面的文章后全明白了。

  • 效果图如下
    JS file dependency graph 2JS文件的依赖关系图2

  • JS文件大小
    JS File Size 2JS文件大小2

  1. 分析包大小问题
  • 从上面的依赖效果图可以明显的看出,有几个包特别大,特别显眼
    • ant-design的Icons文件
    • moment文件
    • quill文件
    • highlight.js文件
  1. ant-design的Icons文件优化
  • 这是ant-design的一个问题
  • 而关于上面的问题,我建议你们直接看链接最下面的部分。(上面的一群人聊了半天,不知所以然,各种链接来回跳,也没找到结果)
  • 核心的几句话。
    JS SolutionsJS解决方案
    TS SolutionsTS解决方案
  • 通过了自己的理解,一个要自己引入相应的Icon,另一个是要在webpack里面进行配置
  • 增加antdIcon.ts代码,引入相应的Icon

    // 自己项目里面用到的Icon
    export {
        default as FileOutline,
    } from '@ant-design/icons/lib/outline/FileOutline';
    
    // antd的message组建内部用到的Icon 把源代码复制过来。
    // var iconType = {
    //     info: 'info-circle',
    //     success: 'check-circle',
    //     error: 'close-circle',
    //     warning: 'exclamation-circle',
    //     loading: 'loading'
    // }[args.type]
    
    // message info
    export {
        default as InfoCircleTwoTone,
    } from '@ant-design/icons/lib/twotone/InfoCircleTwoTone'; // message success export { default as CheckCircleTwoTone, } from '@ant-design/icons/lib/twotone/CheckCircleTwoTone'; // message error export { default as CloseCircleTwoTone, } from '@ant-design/icons/lib/twotone/CloseCircleTwoTone'; // message warning export { default as ExclamationCircleTwoTone, } from '@ant-design/icons/lib/twotone/ExclamationCircleTwoTone'; // message loading export { default as LoadingOutline, } from '@ant-design/icons/lib/outline/LoadingOutline';
     
  • 修改 webpack 配置

    module.exports = {
        resolve: {
            modules: [path.resolve(__dirname, './src'), 'node_modules'], // <- 追加代码
            extensions: ['.ts', '.js', '.vue', '.json'], // <- 追加代码
            alias: {
                vue$: 'vue/dist/vue.esm.js',
                '@ant-design/icons/lib/dist$': path.resolve(__dirname, './src/tools/antdIcon.ts'), // <- 追加代码
            },
            plugins: [ // <- 追加代码
                new TsconfigPathsPlugin({
                    configFile: path.resolve(__dirname, './tsconfig.json'), }), ], },

     

  • 再一次编译,是不是发现已经看不到Icon了,本来就应该这样,我的项目中根本没用几个Icon
    FIG 3 dependent effect依赖效果图3

  • JS文件的大小,直接减少了500K左右
    JS File size 3JS文件大小3

  1. moment文件优化
  • 这是个Ant-design内部依赖的语言文件,我的程序里面本身没有引用,我主要用到的是里面的中文,所以,中文以外的我全部在webpack里面设置忽略就行了
    module.exports = {
        plugins: [
            // 只读取(zh-cn)文件。
            new webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(zh-cn)$/),
        ],
    } 
  1. quill文件优化
  • 这个是我用到的富文本功能,本身对这个组件不太了解,但又必须要用到,也没什么太好优化方法,索性,把它抽离成一个单独的共通JS文件,这样起码有2个组建同时调用这个富文本的情况下,只有第一个掉用的那个需要引入JS文件,第二次的那个会直接利用浏览器的缓存来调用这个JS文件的,也有一定程度的优化效果。

  • 所以我修改了抽离共通组件的那部分代码

    module.exports = {
        optimization: {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        chunks: 'all',
                        test: /[\\/](quill)[\\/]/, // <- 就是简单修改了下匹配规则
                        name: 'vendor',
                        minChunks: 1,
                        maxInitialRequests: 5,
                        minSize: 0, priority: 100, }, common: { chunks: 'all', test: /[\\/]src[\\/]js[\\/]/, name: 'common', minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 1, }, }, }, runtimeChunk: { name: 'manifest', }, } } 
  • 7和8修改之后的效果
    FIG 4 Effect dependency依赖关系效果图4

  • 7和8修改之后的JS文件大小
    JS File Size 4JS文件大小4

  1. highlight.js文件优化
  • 这个主要是我用markdown编辑器的时候,用来给文字着色的。没有这个,在编写markdown的时候,内容非常的丑陋。
  • 但是这个东西的语法太多了,导致这个包非常的大,我编写的时候,只需要利用其中的几种情况而已,我先随便定几种情况,反正是自己的项目,有不够的以后随时再追加(正式项目的话请做好调研)
  • highlight.js官方说明

    // 按需加载的写法
    import hljs from 'highlight.js/lib/highlight';
    import javascript from 'highlight.js/lib/languages/javascript';
    hljs.registerLanguage('javascript', javascript);

     

  • 改完文件以后再看依赖关系
    5 dependency renderings依赖关系效果图5

  • JS文件大小
    JS File Size 5JS文件大小5

  • 至此,我觉得以我现在的水平代码已经没有什么好调整了,main文件还是有点大,我也已经尽力了。

  1. 服务开启Gzip代码压缩
  • 我用的是nginx服务器,它可以开启Gzip,代码压缩率非常可观。200k文件直接被它压缩到几十k。
  • 原本还有点小卡的网站,在启用了Gzip之后,变得一点也不卡了。

  • 修改nginx配置,这里有个小的坑(最后还给我来一个坑),随便找个网站复制下,大致都长下面这样,最后要重启nginx服务,让它读取最新配置nginx -s reload。如果你用的是docker请输入docker exec -it 容器名字 service nginx reload

    gzip on;
    gzip_min_length  5k;
    gzip_buffers     4 16k;
    #gzip_http_version 1.0;
    gzip_comp_level 3;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;

     

  • 坑在哪里?你自己看吧,说出来都是泪啊

  • Gzip有啥缺点? 我也不太清楚,第一应该是它不支持IE6以及IE6以下的浏览器。还有人说他不利于SEO,但也有人说他利于SEO,是真是假去问百度。网上大部分人觉的他的优点大于缺点。

  • 谢谢大家。

 

原文连接:https://www.cnblogs.com/shenxf/p/10879535.html

前言

  • 这段时间,本人自己做了一个vue画面部署到自己的服务器上,发现运行速度慢的的惊人,虽然服务器很渣(本人没什么钱,只能租最差的服务器,主要是给自己学习用的),但是这样开发出来的网站简直不能用,所以就查阅各种资料和网站,一步一步把代码包优化。这篇文章主要是把我调优的过程记录下来。
  • 项目的基础框架是通过TypeScript官网取得的。各种基础框架模版
  • 项目的构成 vue + ant-design + mysql + TypeScript
  • vue项目地址
  • 最后,关于如何在vue里面实现按需加载,请自行查阅相关资料。以及,webpack的基础知识本文也不做介绍,可以参照我github的 学习笔记
  • [原文地址](http://shenxf.top/2019/05/16/20190516-vueSpeedUp/)

调优过程

  1. 禁用webpack的devtools
  • 打包出来的js文件非常大,每个js文件竟然达到了3~4Mbs,这样的体积对于我的服务带宽来说根本负担不起。打开画面必卡。
  • 究其原因,是因为webpack里面启用了sourceMap,以便于调试。但是这在发布以后就完全没有用了。
  • webpack配置,里面有这句话,把这句话注释掉。原本3~4Mbs的文件,变成了1Mbs文件。压缩了3倍以上。
  • // 启用sourceMap
    devtool: '#source-map'

     

  1. 抽离css样式等
  • 这个虽然对于改善效果不明显,但是好的分类对于发现问题的本质有很大的帮助。另外,css样式分离后要自己进行压缩。

    // *************webpack需要引入的包*************************
    // 抽离css样式
    let MiniCssExtractPlugin = require('mini-css-extract-plugin');
    // 用来压缩分离出来的css样式
    let OptimizeCss =  require('optimize-css-assets-webpack-plugin');
    // 用来压缩js
    let UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    
    // *************webpack相关配置部分*************************
    module.exports = {
        optimization: {
            // 优化项
            minimizer: [
                new OptimizeCss(), // 压缩css
                new UglifyJsPlugin({ // 压缩js
                    cache: true, // 是否用缓存
                    parallel: true, // 并发打包
                    sourceMap: false, // es6 -> es5 转换时会用到
     }), ], } // 中间部分省略 // 抽离css样式  plugins: [ new MiniCssExtractPlugin({ filename: 'css/[name].css', // 抽离出来样式的名字  }), ], }
     
  • 抽离之后,现在项目生成文件的大小是这样。
    JS file sizeJS文件的大小

  1. 启用依赖关系可视化工具
  • 完成上面工作之后,陷入了茫然,网站还是很卡,不知道还能怎么调优,在翻阅了很多网站资料以后,发现了一个依赖关系可视化工具,这对于我来说是一个重大的突破口

    // 依赖关系可视化
    // *************webpack需要引入的包*************************
    const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
    
    // *************webpack相关配置部分*************************
    module.exports = {
    
        // 启动依赖关系可视化窗口,绑定端口8919
        plugins: [
            new BundleAnalyzerPlugin({ analyzerPort: 8919 }),
        ],
    }
     
  • 重新进行编译以后的效果图
    JS file dependency graphJS文件的依赖关系图

  • 通过这个效果图可以很明显的看出js文件里面包含什么依赖,我就是通过这个线索来进行优化的。

  1. 抽离共通部分
  • 为了方便我调查,我把共通的依赖部分都抽离出来了。而这个功能是webpack4自带的,如果是之前或者更早版本的webpack,需要引入第三方组件CommonsChunkPlugin这里不做介绍。

    module.exports = {
        optimization: {
            //打包 公共文件
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        //node_modules内的依赖库
                        chunks: 'all',
                        test: /[\\/](node_modules)[\\/]/, // 文件路径里面带有node_modules 都抽离出来做共通
                        name: 'vendor',
                        minChunks: 1, //被不同entry引用次数(import),1次的话没必要提取
                        maxInitialRequests: 5,
                        minSize: 0, priority: 100, // enforce: true?  }, common: { // ‘src/js’ 下的js文件 chunks: 'all', test: /[\\/]src[\\/]js[\\/]/, //也可以值文件/[\\/]src[\\/]js[\\/].*\.js/, name: 'common', //生成文件名,依据output规则 minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 1, }, }, }, runtimeChunk: { name: 'manifest', }, } } 
  • 一开始我对于这个属性的名字难以理解,以至于没有效果,看了下面的文章后全明白了。

  • 效果图如下
    JS file dependency graph 2JS文件的依赖关系图2

  • JS文件大小
    JS File Size 2JS文件大小2

  1. 分析包大小问题
  • 从上面的依赖效果图可以明显的看出,有几个包特别大,特别显眼
    • ant-design的Icons文件
    • moment文件
    • quill文件
    • highlight.js文件
  1. ant-design的Icons文件优化
  • 这是ant-design的一个问题
  • 而关于上面的问题,我建议你们直接看链接最下面的部分。(上面的一群人聊了半天,不知所以然,各种链接来回跳,也没找到结果)
  • 核心的几句话。
    JS SolutionsJS解决方案
    TS SolutionsTS解决方案
  • 通过了自己的理解,一个要自己引入相应的Icon,另一个是要在webpack里面进行配置
  • 增加antdIcon.ts代码,引入相应的Icon

    // 自己项目里面用到的Icon
    export {
        default as FileOutline,
    } from '@ant-design/icons/lib/outline/FileOutline';
    
    // antd的message组建内部用到的Icon 把源代码复制过来。
    // var iconType = {
    //     info: 'info-circle',
    //     success: 'check-circle',
    //     error: 'close-circle',
    //     warning: 'exclamation-circle',
    //     loading: 'loading'
    // }[args.type]
    
    // message info
    export {
        default as InfoCircleTwoTone,
    } from '@ant-design/icons/lib/twotone/InfoCircleTwoTone'; // message success export { default as CheckCircleTwoTone, } from '@ant-design/icons/lib/twotone/CheckCircleTwoTone'; // message error export { default as CloseCircleTwoTone, } from '@ant-design/icons/lib/twotone/CloseCircleTwoTone'; // message warning export { default as ExclamationCircleTwoTone, } from '@ant-design/icons/lib/twotone/ExclamationCircleTwoTone'; // message loading export { default as LoadingOutline, } from '@ant-design/icons/lib/outline/LoadingOutline';
     
  • 修改 webpack 配置

    module.exports = {
        resolve: {
            modules: [path.resolve(__dirname, './src'), 'node_modules'], // <- 追加代码
            extensions: ['.ts', '.js', '.vue', '.json'], // <- 追加代码
            alias: {
                vue$: 'vue/dist/vue.esm.js',
                '@ant-design/icons/lib/dist$': path.resolve(__dirname, './src/tools/antdIcon.ts'), // <- 追加代码
            },
            plugins: [ // <- 追加代码
                new TsconfigPathsPlugin({
                    configFile: path.resolve(__dirname, './tsconfig.json'), }), ], },

     

  • 再一次编译,是不是发现已经看不到Icon了,本来就应该这样,我的项目中根本没用几个Icon
    FIG 3 dependent effect依赖效果图3

  • JS文件的大小,直接减少了500K左右
    JS File size 3JS文件大小3

  1. moment文件优化
  • 这是个Ant-design内部依赖的语言文件,我的程序里面本身没有引用,我主要用到的是里面的中文,所以,中文以外的我全部在webpack里面设置忽略就行了
    module.exports = {
        plugins: [
            // 只读取(zh-cn)文件。
            new webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(zh-cn)$/),
        ],
    } 
  1. quill文件优化
  • 这个是我用到的富文本功能,本身对这个组件不太了解,但又必须要用到,也没什么太好优化方法,索性,把它抽离成一个单独的共通JS文件,这样起码有2个组建同时调用这个富文本的情况下,只有第一个掉用的那个需要引入JS文件,第二次的那个会直接利用浏览器的缓存来调用这个JS文件的,也有一定程度的优化效果。

  • 所以我修改了抽离共通组件的那部分代码

    module.exports = {
        optimization: {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        chunks: 'all',
                        test: /[\\/](quill)[\\/]/, // <- 就是简单修改了下匹配规则
                        name: 'vendor',
                        minChunks: 1,
                        maxInitialRequests: 5,
                        minSize: 0, priority: 100, }, common: { chunks: 'all', test: /[\\/]src[\\/]js[\\/]/, name: 'common', minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 1, }, }, }, runtimeChunk: { name: 'manifest', }, } } 
  • 7和8修改之后的效果
    FIG 4 Effect dependency依赖关系效果图4

  • 7和8修改之后的JS文件大小
    JS File Size 4JS文件大小4

  1. highlight.js文件优化
  • 这个主要是我用markdown编辑器的时候,用来给文字着色的。没有这个,在编写markdown的时候,内容非常的丑陋。
  • 但是这个东西的语法太多了,导致这个包非常的大,我编写的时候,只需要利用其中的几种情况而已,我先随便定几种情况,反正是自己的项目,有不够的以后随时再追加(正式项目的话请做好调研)
  • highlight.js官方说明

    // 按需加载的写法
    import hljs from 'highlight.js/lib/highlight';
    import javascript from 'highlight.js/lib/languages/javascript';
    hljs.registerLanguage('javascript', javascript);

     

  • After completion of the file to change the look dependencies dependency renderings 5
    5 dependency renderings

  • JS File Size JS File Size 5
    JS File Size 5

  • At this point, I think to my present level code has nothing to adjust, main document is still a little big, and I've tried.

  1. Service enabling Gzip compression codes
  • I use nginx server, it can open Gzip, code compression rate is very impressive. 200k compressed files directly to it dozens of k.
  • Originally there is a small card site, after enabling the Gzip, is not to become a card.

  • Modify nginx configuration, there is a small pit (finally gave me a pit), just to find a copy at the site, approximately follows are long, and finally to restart nginx service, it reads the latest configuration nginx -s reload. If you use the dockerEnterdocker exec -it 容器名字 service nginx reload

    gzip on;
    gzip_min_length  5k;
    gzip_buffers     4 16k;
    #gzip_http_version 1.0;
    gzip_comp_level 3;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;

     

  • Pit Where? You can see for yourself, speak out are tears ah pit

  • Gzip what's the drawback? I'm not sure, should be the first IE6 and IE6 it does not support the following browsers. Others say he is not conducive to SEO, but some say he was conducive to SEO, it is true to ask Baidu. Most people feel his online advantages outweigh the disadvantages.

  • thank you all.

 

Guess you like

Origin www.cnblogs.com/bigmango/p/12356260.html