前言

最近发现前端框架页面加载非常的慢,为了解决这个问题,项目组决定将webpacke打包后的文件部署到腾讯COS上面,这样可以提高加载速度。

准备

我们的前端框架使用的是vue.js2.0 + vue-cli大家可以根据自己的环境进行调整,下面是具体的操作。

操作

1、添加依赖包

"webpack-cos-plugin-qapm": "^1.2.0"

"scripts": {
    "serve": "vue-cli-service serve",
    "serve-local": "vue-cli-service serve --mode local",
    "build": "vue-cli-service build --mode staging",
    "build:stage": "vue-cli-service build --mode staging",
    "build:production": "vue-cli-service build --mode production",
    "build:uat": "vue-cli-service build --mode uat",
    "build:prod": "vue-cli-service build --mode production",
    "build:report": "vue-cli-service build --report",
    "preview": "node build/index.js --preview",
    "lint": "eslint --ext .js,.vue src/",
    "lint-fix": "eslint --fix --ext .js,.vue src/",
    "lint:report": "npx eslint --ext .js,.vue src/  -f json",
    "lint:report:html": "npx eslint --ext .js,.vue src/  -f html -o report.html"
  },

2、配置vue.config.js

'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const QcCOSPlugin = require('webpack-cos-plugin-qapm')
const { version } = require('./package.json')

function resolve (dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '管理平台' // 标题

const port = process.env.port || process.env.npm_config_port || 84 // 端口


console.log('------process.env.ENV------->', process.env.ENV, process.env.ENV_NAME)
let BASE_URL = '/'

let COS_BUCKET = ''
// cdn的自定义域名+cos保存路径+版本号
let baseCdn = ''
if (process.env.ENV_NAME === 'PROD') {
  COS_BUCKET = '611-prod-1317971397'
  baseCdn = 'abc.com/611_front/611-web-admin/' + version
}
if (process.env.ENV_NAME === 'UAT') {
  COS_BUCKET = '611-dev-1317971397'
  baseCdn = 'uat.abc.com/611_front/611-web-admin/' + version
}

let plugins = process.env.ENV_NAME === 'PROD' || process.env.ENV_NAME === 'UAT' ? [
  new QcCOSPlugin({
    auth: {
      SecretId: 'xxx', // 在腾讯 COS 控制台获取
      SecretKey: 'xxxx' // 在腾讯 COS 控制台获取
    },
    bucket: {
      Bucket: COS_BUCKET, // COS 存储空间, 在腾讯 COS 控制台获取
      Region: 'ap-guangzhou'// COS 服务节点, 示例: oss-cn-hangzhou
    },
    cosBaseDir: 'front',
    useVersion: true,
    // exclude: /.*\.spaceEva$/,
    removeMode: false,
    project: 'web-admin' // 项目名(用于存放文件的直接目录)
  })
] : []

let localProxys = {}
if (process.env.ENV === 'local') {
  localProxys = {
    ...localProxys,
    '/plus-operation': {
      target: process.env.HOST_PLUS_OPERATION,
      changeOrigin: true,
      pathRewrite: {
        ['^' + '/plus-operation']: ''
      }
    },
    '/plus-schedule': {
      target: process.env.HOST_PLUS_SCHEDULE,
      changeOrigin: true,
      pathRewrite: {
        ['^' + '/plus-schedule']: ''
      }
    },
    '/plus-nhs': {
      target: process.env.HOST_PLUS_NHS,
      changeOrigin: true,
      pathRewrite: {
        ['^' + '/plus-nhs']: ''
      }
    },
    '/plus-iot': {
      target: process.env.HOST_PLUS_IOT,
      changeOrigin: true,
      pathRewrite: {
        ['^' + '/plus-iot']: ''
      }
    }
  }
}

// vue.config.js 配置说明
// 官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.shimao.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.shimao.com/admin/,则设置 baseUrl 为 /admin/。
  publicPath: BASE_URL,
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: 'dist',
  runtimeCompiler: true,
  // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  assetsDir: 'static',
  // 是否开启eslint保存检测,有效值:ture | false | 'error'
  lintOnSave: false,
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    host: '0.0.0.0',
    port: port,
    open: true,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://172.16.0.115',
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      },
      ...localProxys

    },
    disableHostCheck: true
  },
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
        '@@': resolve('src/x7')
      }
    },
    plugins: plugins
  },
  chainWebpack (config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    config.entry('index').add('babel-polyfill')
    if (process.env.ENV === 'local') {
      config.plugin('define').tap((args) => {
        // dev server 监听端口
        args[0]['process.env'].plusOperationHost = '\'http://localhost:1024\''
        args[0]['process.env'].plusNhsHost = '\'http://localhost:1024\''
        args[0]['process.env'].plusSchedulingHost = '\'http://localhost:1024\''
        args[0]['process.env'].plusIotHost = '\'http://localhost:1024\''
        return args
      })
    }

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single'),
          {
            from: path.resolve(__dirname, './public/robots.txt'), // 防爬虫文件
            to: './'// 到根目录下
          }
        }
      )
  }
}

3、配置vue-router

var router = new Router({
  mode: 'history',
  // 访问的路径路由 
  base: '/',
  routes: mergeRouters
})

4、发布并查看效果
image.png
image.png

最后打开前端页面,确实比之前要快!

总结

1、注意下dev、uat、prod环境,因为只有uat和prod才需要上传,开发环境不需要
2、注意一下vue-router里面的base设置和webpack里面的publicPath配置,前端是设置路由访问前缀路径,后面是设置文件打包前缀路径


Awbeci
3.1k 声望213 粉丝

Awbeci