vue项目打包优化及发布

206 阅读2分钟

项目根目录创建webpack.dll.conf.js

const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: {
    vender: ['vue', 'vue-router', 'axios', 'vuex']
  },
  output: {
    path: path.join(__dirname, '../public/static'),
    filename: "[name].dll.js",
    library: "[name]_library"
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, ".", "[name]-manifest.json"),
      name: "[name]_library"
    })
  ]
}

vue.config.js 配置


const path = require('path')
const TerserPlugin = require('terser-webpack-plugin')
const webpack = require('webpack')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const CompressionPlugin = require("compression-webpack-plugin")
const isProduction = process.env.NODE_ENV === 'production'

const name = '大数据人才库'

const resolve = (dir) => path.join(__dirname, dir)

module.exports = {
  outputDir: 'front',
  lintOnSave: true,
  productionSourceMap: false,
  devServer: {
    hot: true,
    proxy: {
      '/gov_api': {
        target: 'http://gov_rck.yunzedd.com/'
        // changeOrigin: true,
      },
      '/api': {
        target: 'http://gov_rck.yunzedd.com/'
        // changeOrigin: true,
      }
    }
  },
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "styles/vars.scss";`
      }
    }
  },
  chainWebpack: config => {
    // 配置路径别名
    config.resolve.alias
      .set('apis', resolve('src/apis'))
      .set('comps', resolve('src/components'))
      .set('views', resolve('src/views'))
      .set('styles', resolve('src/styles'))
      .set('imgs', resolve('src/assets/images'))
      .set('utils', resolve('src/utils'))

    /* 添加分析工具 */
    if (isProduction) {
      // 图片压缩
      config.module
        .rule('images')
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({ bypassOnDebug: true })
        .end()
    }
  },
  configureWebpack: config => {
    config.name = name

    if (isProduction) {
      // dll优化
      config.plugins.push(new webpack.DllReferencePlugin({
        context: process.cwd(), //当前目录
        manifest: require('./build/vender-manifest.json')
      }))
      // 将打包出来文件动态引入index.html
      config.plugins.push(
        new AddAssetHtmlPlugin({
          // dll文件位置
          filepath: path.resolve(__dirname, './public/static/vender.dll.js'),
          // dll 引用路径
          publicPath: './static',
          outputPath: './static', // 输出的目录地址
        })
      )
      config.optimization = {
        splitChunks: {
          chunks: 'all', // 仅提取按需载入的module
          cacheGroups: { // 缓存组配置,默认有vendors和default
            'vendors': {
              test: /[\\/]node_modules[\\/]/, // 匹配需拆分chunk的目录
              priority: -20
            },
            'element-ui': {
              name: 'element-ui',
              test: /[\\/]node_modules[\\/]element-ui[\\/]/,
              priority: -10
            },
            'echarts': {
              name: 'echarts',
              test: /[\\/]node_modules[\\/]echarts[\\/]/,
              priority: -10
            },
            'element-china-area-data': {
              name: 'element-china-area-data',
              test: /[\\/]node_modules[\\/]element-china-area-data[\\/]/,
              priority: -10
            },
            default: {
              minChunks: 2, // 覆盖外层minChunks,用于提取被引用指定次数的公共模块,这里默认2次
              priority: -20,
              reuseExistingChunk: true // 是否重用已存在的chunk
            }
          }
        }
      }
      config.plugins.push(
        // 生产环境自动删除console
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log', 'console.error'] // 移除console
            }
          }
        })
      )
      return {
        plugins: [
          new CompressionPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
            threshold: 10240, // 10k以上压缩
            minRatio: 0.8, // 压缩质量
            // deleteOriginalAssets: true // 是否删除源文件
          })
        ]
      }
    }
  }
}

项目根目录创建deploy.sh

#!/bin/bash
# 压缩文件
tar -zcvf admin-talent-pool.tar.gz front
echo "[文件压缩完成!]"

# scp 将压缩包上传到服务器
scp  admin-talent-pool.tar.gz root@39.101.180.5:/data/gov_rck
echo "[文件上传完成完成!]"

# shh链接服务器
ssh root@39.101.180.5  << remotessh
cd  /data/gov_rck
rm -rf front
mkdir front 
tar -zxvf admin-talent-pool.tar.gz -C /data/gov_rck 
rm -rf admin-talent-pool.tar.gz
exit
remotessh

rm -rf admin-talent-pool.tar.gz
echo "[删除本地压缩包!]"

package.json 下的scripts

"deploy": "yarn dll && yarn build && sh deploy.sh"