Vue project packaging process

After vue scaffolding version 3.0, the config, build and static folders have been removed, so we have to create a new vue.config.js file when packaging

1. Close productionSourceMap

When closing SourceMap, we can modify the path during packaging and change the name of the packaged folder

module.exports={
    
    
	productionSourceMap:false,//关闭productionSourceMap
	pubilcPath:"./",//更改图片路径
	outputDir:"ting"//打包重命名
}

2. Picture compression

  • Install the plugin cnpm install image-webpack-loader --save-dev

Now put the code under outputDir: "ting" (remember to use, separate)

 chainWebpack: config => {
    
    
        // ============压缩图片 start============
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({
    
     bypassOnDebug: true })
            .end()
// ============压缩图片 end============
}

3. Turn on CDN acceleration

Defined above module.exports

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development'
// 本地环境是否需要使用cdn
const devNeedCdn = true
// cdn链接
const cdn = {
    
    
  // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
  externals: {
    
    
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter',
    'marked': 'marked',
    'highlight.js': 'hljs',
    'nprogress': 'NProgress',
    'axios': 'axios',
    'element-ui': 'ELEMENT',
    'lodash': '_',
    'echarts': 'echarts',
    'vue-quill-editor': 'VueQuillEditor'
  },
  // cdn的css链接
  css: [
    'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css',
    'https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css',
    'https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css',
    'https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css',
    'https://cdn.staticfile.org/element-ui/2.4.5/theme-chalk/index.css'
  ],
  // cdn的js链接
  js: [
    'https://cdn.staticfile.org/vue/2.6.10/vue.min.js',
    'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
    'https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js',
    'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js',
    'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
    'https://cdn.staticfile.org/element-ui/2.4.5/index.js',
    'https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js',
    'https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js',
    'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-quill-editor.js'
  ]
}

Write in chainWebpack

        // ============注入cdn start============
        config.plugin('html').tap(args => {
    
    
            // 生产环境或本地需要cdn时,才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ============注入cdn start============
    },
    configureWebpack: config => {
    
    
        // 用cdn方式引入,则构建时要忽略相关资源
        if (isProduction || devNeedCdn) config.externals = cdn.externals
    }

In the index.htmlintroduction of a link used in the CDN, specific code as follows ↓

  • Under title, in head
	 <!-- 使用CDN的CSS文件 -->
 <% for (var i in htmlWebpackPlugin.options.cdn &&
  htmlWebpackPlugin.options.cdn.css) { %>
  <link
          href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"
          rel="stylesheet"
  />
  <% } %>
  <!-- 使用CDN的CSS文件 -->

The bottom layer in the body

  <!-- 使用CDN的JS文件 -->
 <% for (var i in htmlWebpackPlugin.options.cdn &&
  htmlWebpackPlugin.options.cdn.js) { %>
  <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
  <% } %>
  <!-- 使用CDN的JS文件 -->

4. Code compression

Vue will automatically compress the code, uglify.js has stopped maintenance, but the removal of console.log is still indispensable for our door

  • Install the plugin cnpm i -D uglifyjs-webpack-plugin

module.exports above code

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

Introduce code compression in the configureWebpack module

// 代码压缩
config.plugins.push(
    new UglifyJsPlugin({
    
    
        uglifyOptions: {
    
    
            //生产环境自动删除console
            compress: {
    
    
                drop_debugger: true,
                drop_console: true,
                pure_funcs: ['console.log']
            }
        },
        sourceMap: false,
        parallel: true
    })
)

5. Common code extraction

Written in the configureWebpack module

// 公共代码抽离
config.optimization = {
    
    
    splitChunks: {
    
    
        cacheGroups: {
    
    
            vendor: {
    
    
                chunks: 'all',
                test: /node_modules/,
                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: 60
            },
            styles: {
    
    
                name: 'styles',
                test: /\.(sa|sc|c)ss$/,
                chunks: 'all',
                enforce: true
            },
            runtimeChunk: {
    
    
                name: 'manifest'
            }
        }
    }
}

6. Skeleton screen

  • Npm install vue-skeleton-webpack-plugin

Create a new Skeleton folder under src, in which index.js and index.vue are newly created, and the following content is written in them. Among them, the index.vue page style of the skeleton screen should be edited by yourself

index.js

import Vue from 'vue'
import Skeleton from './index.vue'
export default new Vue({
    
    
  components: {
    
    
    Skeleton
  },
  template: '<Skeleton />'
})

Skeleton screen page

<template>
  <div class="skeleton-wrapper">
    <header class="skeleton-header"></header>
    <section class="skeleton-block">
      <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTA4MCAyNjEiPjxkZWZzPjxwYXRoIGlkPSJiIiBkPSJNMCAwaDEwODB2MjYwSDB6Ii8+PGZpbHRlciBpZD0iYSIgd2lkdGg9IjIwMCUiIGhlaWdodD0iMjAwJSIgeD0iLTUwJSIgeT0iLTUwJSIgZmlsdGVyVW5pdHM9Im9iamVjdEJvdW5kaW5nQm94Ij48ZmVPZmZzZXQgZHk9Ii0xIiBpbj0iU291cmNlQWxwaGEiIHJlc3VsdD0ic2hhZG93T2Zmc2V0T3V0ZXIxIi8+PGZlQ29sb3JNYXRyaXggaW49InNoYWRvd09mZnNldE91dGVyMSIgdmFsdWVzPSIwIDAgMCAwIDAuOTMzMzMzMzMzIDAgMCAwIDAgMC45Mz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XRyaXggaW49InNoYWRvd09mZnNldE91dGVyMSIgdmFsdWVzPSIwIDAgMCAwIDAuOTMzMzMzMzMzIDAgMCAwIDAgMC45MzMzMzMzMzMgMCAwIDAgMCAwLjkzMzMzMzMzMyAwIDAgMCAxIDAiLz48L2ZpbHRlcj48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwIDEpIj48dXNlIGZpbGw9IiMwMDAiIGZpbHRlcj0idXJsKCNhKSIgeGxpbms6aHJlZj0iI2IiLz48dXNlIGZpbGw9IiNGRkYiIHhsaW5rOmhyZWY9IiNiIi8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCA0NGg1MzN2NDZIMjMweiIvPjxyZWN0IHdpZHRoPSIxNzIiIGhlaWdodD0iMTcyIiB4PSIzMCIgeT0iNDQiIGZpbGw9IiNGNkY2RjYiIHJ4PSI0Ii8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCAxMThoMzY5djMwSDIzMHpNMjMwIDE4MmgzMjN2MzBIMjMwek04MTIgMTE1aDIzOHYzOUg4MTJ6TTgwOCAxODRoMjQydjMwSDgwOHpNOTE3IDQ4aDEzM3YzN0g5MTd6Ii8+PC9nPjwvc3ZnPg==">
    </section>
  </div>
</template>
 
<script>
  export default {
     
     
    name: 'skeleton'
  }
</script>
 
<style scoped>
  .skeleton-header {
     
     
    height: 40px;
    background: #1976d2;
    padding:0;
    margin: 0;
    width: 100%;
  }
  .skeleton-block {
     
     
    display: flex;
    flex-direction: column;
    padding-top: 8px;
  }
 
</style>

vue.config.js

above module.exports

//骨架屏渲染
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')

//path引入
const path = require('path')

Join in configureWebpack

config.plugins.push(new SkeletonWebpackPlugin({
    
    
      webpackConfig: {
    
    
        entry: {
    
    
          app: path.join(__dirname, './src/Skeleton/index.js'),
        },
      },
      minimize: true,
      quiet: true,
      // 如果不设置那么所有的路由都会共享这个骨架屏组件
      router: {
    
    
        mode: 'hash',
        // 给对应的路由设置对应的骨架屏组件,skeletonId的值根据组件设置的id
        routes: [
          {
    
     path: '/list', skeletonId: 'skeleton' }
        ]
    }))

7. Turn on Gzip compression

注意的是,服务器上nginx也必须开启gzip才能生效

vue.config.js

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')

module.exports = {
    
    
    productionSourceMap: false,
    configureWebpack: config => {
    
    
        // 生产环境相关配置
        if (isProduction) {
    
    
            //gzip压缩
            const productionGzipExtensions = ['html', 'js', 'css']
            config.plugins.push(
                new CompressionWebpackPlugin({
    
    
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: new RegExp(
                        '\\.(' + productionGzipExtensions.join('|') + ')$'
                    ),
                    threshold: 10240, // 只有大小大于该值的资源会被处理 10240
                    minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
                    deleteOriginalAssets: false // 删除原文件
                })
            )
        }
    }
}

nginx

    # 开启gzip
    gzip on;

    # 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
    gzip_min_length 1k;

    # gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
    gzip_comp_level 2;

    # 进行压缩的文件类型。javascript有多种形式,后面的图片压缩不需要的可以自行删除
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

    # 是否在http header中添加Vary: Accept-Encoding,建议开启
    gzip_vary on;

    # 设置压缩所需要的缓冲区大小     
    gzip_buffers 4 16k;

Guess you like

Origin blog.csdn.net/shiqina/article/details/112391509