本文主要讲了vue-config.js的几个常用配置项,和打包优化npm的插件。
更详细的配置项用法请浏览官网:
Vue CLI 官网:https://cli.vuejs.org/zh/config/#pages
webpack官网:https://webpack.js.org/plugins/compression-webpack-plugin/#root

一、TerserWebpackPlugin

它是用来打包压缩混淆 ,打包的时候可以去除console,debugger的等。

在vue项目中怎么找到webpack的版本?
一般在package.json,没有的话就全局搜索一下。

webpack官网链接
在这里插入图片描述
用法说明

vue-config.js

const TerserPlugin = require("terser-webpack-plugin");

 // 用法压缩混淆
    plugins.push(new TerserPlugin({
        terserOptions: {
            output: {
                comments: false, // 去除注释
            },
            warnings: false, // 去除黄色警告,
            compress: {
                drop_console: true,
                drop_debugger: true, // 特定情况需要利用debugger防止调试
                pure_funcs: ['console.log'], // 移除console.log 避免console.error
            }
        }
    }))

二、transpileDependencies

vue-cli 官网地址
在这里插入图片描述
优点:transpileDependencies 为true 的时候可以把es6以上的语法改为es5,便于浏览器兼容,它也可以指定某个库,局部编译。
缺点:打包速度比较慢。

vue-config.js

module.exports = {

    ...defineConfig({
        transpileDependencies: true  // 它也可以这样写 ['element-ui'] 指定某个库在打包的时候需要编译
    }),
}

三、productionSourceMap

主要用于减少打包后的体积
在这里插入图片描述
vue-config.js

  productionSourceMap: false,

四、devServer

前端vue配置代理
在这里插入图片描述
vue-cli 5.0配置代理的方法如下,配置代理的时候一定要看清楚webpack的版本,不同的webpack版本写法有差异。

vue-config.js

module.exports = defineConfig({
  devServer: {
    port: 9000,
    server: 'https',
    client: {
      webSocketURL: 'auto://0.0.0.0:0/ws'
    },
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    proxy: {
      //第一种写法
      '/api': { //代理接口的名字
        target: {
          host: '111.XXX.XXX.XXX',
          protocol:'https:',  //可以代理https 或者http
          port: '9002'
        },
        ignorePath: false,
        changeOrigin: true,
        secure: false
      },
      //第二种写法
       '/baidu':{
        target:'http://baidu.com'
       }
  },

五、compression-webpack-plugin

gzip压缩

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

vue-config.js

const CompressionWebpackPlugin = require('compression-webpack-plugin')
 // Gzip压缩大于10kb以上的js|json|css文件
    plugins.push(new CompressionWebpackPlugin({
        test:/\.(js|json|css)$/i,  // 图片一般不Gzip压缩 webpack-image-loader
        threshold:10240, // 只有在10kb以上才压缩
    }))

为何要使用gzip压缩?
打包的时候开启gzip可以很大程度减少包的大小,页面大小可以变为原来的30%甚至更小,非常适合于上线部署。更小的体积对于用户体验来说就意味着更快的加载速度以及更好的用户体验。

为什么gzip压缩后页面加载速度提升
浏览器向服务器发出请求,并且在请求头中声明可以使用gzip的编码格式,服务器接受到请求之后,读取压缩后的文件,服务器直接返回给浏览器gzip格式的文件,浏览器进行解压缩,这样以来就节省了服务器压缩的时间。

用法请参考其他原文链接:https://blog.csdn.net/duanhy_love/article/details/125069009

六、cdn加载vue的文件

配置cdn 加载网上的资源,减少本地资源的内存。
这些cdn的链接需要在官网自己找,至于需要加载版本,需要自己在node包查看原来引用的是哪个版本的js。

vue-config.js

//定义cdn的各种链接对象
let cdn = {
    build:{
        js:[
            "https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.min.js",
            "https://unpkg.com/vuex@3.6.2/dist/vuex.min.js",
            'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js',
            'https://unpkg.com/vue-router@3.6.5/dist/vue-router.min.js',
        ]
    },
    dev:{
        js:[],
        css:[]
    }
}

//应用的时候
module.exports = {
    ...defineConfig({
        transpileDependencies: true
    }),
    productionSourceMap:false,
    configureWebpack: {
        devServer: {
            // open: true,
            // host: '127.0.0.1',
            proxy: {
                '/api': {
                    logLevel: 'debug',
                    // "@vue/cli-service": "~5.0.0",
                    logProvider:()=>console,
                    target: 'http://xxx.xxx.xx.xxx:8004/',
                }
            }
        },
        plugins,
        externals
    },
    // 再加工
    chainWebpack(config){
        // 去除html-webpack-plugin
        config.plugin('html').tap(args=>{
            // 只是处理一个html=>index.html
            if (isProduction) {
                args[0].myCdn = cdn.build;
            } else {
                args[0].myCdn = cdn.dev;
            }
            return args;
        })
    }
}

public文件下的index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <!-- 下面这句是加载cdn的文件 -->
    <% for (var i in htmlWebpackPlugin.options.myCdn && htmlWebpackPlugin.options.myCdn.js) { %>
        <script src="<%= htmlWebpackPlugin.options.myCdn.js[i] %>"></script>
    <% } %>

  
  </body>
</html>

七、FileManagePlugin

此文件管理器插件允许您在webpack/rollup/wite构建前后删除、压缩/解压缩(.zip/.tar/.tar.gz)、移动、重命名、复制文件或目录
当打包的dist文件并不是你希望的位置,你想把移位到vue工程外的某个位置,此时可以用到FileManagePlugin。

npm install filemanager-webpack-plugin --save-dev

vue-config.js


const FileManagePlugin = require('filemanager-webpack-plugin')

module.exports = defineConfig({
  configureWebpack: {
    plugins: [
      new FileManagePlugin({
        events: {
          onEnd: {
          //复制某个文件
            delete: [
              {
                source: '../dist',
                options: {
                  force: true
                }
              }
            ],
            copy: [
              {
                source: './demoFile',
                destination: '../test/dist02',
                options: {
                  overwrite: true
                }
              }
            ],
            //可以移动某个文件
            // move: [
            //    { source: './dist/', destination: './test/dist02' }
           // ]

          }
        },
        runOnceInWatchMode: true
      })
    ]
  }
  
  })

八、vue-config.js 配置的demo

vue-config文件 开一个新的项目就配置一次,很容易忘记 ,做个demo记录一下。

const TerserPlugin = require("terser-webpack-plugin");
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'
const { defineConfig } = require('@vue/cli-service')
const version = require('./package.json').version;
const moment = require('moment');

let plugins = [];
let externals = {
    // 'import form的东西': 'CDN向外暴露的对象名'
};
let cdn = {
    build:{
        js:[
            "https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.min.js",
            "https://unpkg.com/vuex@3.6.2/dist/vuex.min.js",
            'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js',
            'https://unpkg.com/vue-router@3.6.5/dist/vue-router.min.js',
        ]
    },
    dev:{
        js:[],
        css:[]
    }
}

// 是生产环境
if (isProduction) {

    // CDN优化 不处理,而是全局使用右边的名字遍历
    externals = {
        vue:'Vue',
        'vue-router':'VueRouter',
        axios:'axios',
        vuex:'Vuex'
    }

    // 压缩混淆
    plugins.push(new TerserPlugin({
        terserOptions: {
            output: {
                comments: false, // 去除注释
            },
            warnings: false, // 去除黄色警告,
            compress: {
                drop_console: true,
                drop_debugger: true, // 特定情况需要利用debugger防止调试
                pure_funcs: ['console.log'], // 移除console.log 避免console.error
            }
        }
    }))
    // Gzip压缩大于10kb以上的js|json|css文件
    plugins.push(new CompressionWebpackPlugin({
        test:/\.(js|json|css)$/i,  // 图片一般不Gzip压缩 webpack-image-loader
        threshold:10240, // 只有在10kb以上才压缩
    }))
}

// 添加版本信息及打包信息
process.env.VUE_APP_VERSION = 'demo version ' + version + ' build ' + moment().format('YYYY-MM-DD HH:mm:ss');

module.exports = defineConfig({
  publicPath: process.env.NODE_ENV === 'production'
    ? './'
    : '/',
  transpileDependencies: true,
  lintOnSave: false,
  outputDir: 'dist',
  productionSourceMap: !isProduction,
  configureWebpack:{
     plugins,
     externals
  },
  devServer: {
    port: 9002,
    server: 'https',
    client: {
      webSocketURL: 'auto://0.0.0.0:0/ws'
    },
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    proxy: {
    //配置多个代理 不止一个后台的时候 可以配置多个代理
  
      [`/${process.env.VUE_APP_BASE_PROXY}`]: { //代理1
        target: {
          host: process.env.VUE_APP_BASE_HOST,
          protocol: 'https',
          port: process.env.VUE_APP_BASE_PORT
        },
        ignorePath: false,
        changeOrigin: true,
        secure: false
      },
      [`/${process.env.VUE_APP_HALL_PROXY}`]: {  //代理2
        target: {
          host: process.env.VUE_APP_BASE_HOST,
          protocol:'https',
          port: process.env.VUE_APP_BASE_PORT
        },
        ignorePath: false,
        changeOrigin: true,
        secure: false
      }
    }
  },
            // 再加工
    chainWebpack(config){
        // 去除html-webpack-plugin
        config.plugin('html').tap(args=>{
            // 只是处理一个html=>index.html
            if (isProduction) {
                args[0].myCdn = cdn.build;
            } else {
                args[0].myCdn = cdn.dev;
            }
            return args;
        })
    }

})

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐