项目上线之前的具体优化策略

746 阅读6分钟

一、项目优化策略

1.生成打包报告

1.vue-cli build --report

2.vue ui可视化面板中的仪表盘和分析面板

2.创建vue.config.js来修改webpack默认配置

3.通过chainWebpack自定义打包入口

自定义打包入口有两种方式:configureWebpack和chainWebpack

最后选择的是chainWebpack来自定义打包入口,分为开发模式下的入口和上线后的入口

具体代码:

关键词process.env.NODE_ENVconfigwhen

 module.exports = {
    
    chainWebpack:config=>{
       
       config.when(process.env.NODE_ENV === 'production',config=>{
            config.entry('app').clear().add('./src/main-prod.js')
        })
        
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
        
    }
 }

4.通过externals加载外部CDN资源

默认情况下,通过import语法引入的第三方依赖包,最终会被打包合并到同一个文件中,从而导致打包成功后,单文件体积过大的问题

image.png

为了解决上述问题,可以通过webpack的externals节点,来配置并加载外部的CDN资源,

凡是声明在externals中的第三方依赖包,都不会被打包,而是去winodw全局直接查找并使用具体对象,比如说vue,echarts等

需要注意的是,这些优化方案都是在项目准备上线时的操作,如果继续想要在开发模式下使用的话,就还保持原来的import写法,否则,本地运行不出来或者空白页面

    #写在发布入口的配置文件下面,
     config.set('externals', {
                vue: 'Vue',
                'vue-router': 'VueRouter',
                axios: 'axios',
                lodash: '_',
                echarts: 'echarts',
                nprogress: 'NProgress',
                'vue-quill-editor': 'VueQuillEditor'
            })

之后,我们需要在public/index.html中,添加我们上面各自的CDN资源

    <script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js"></script>
    <script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
    <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
      <!-- 富文本编辑器的 js 文件 -->
    <script src="https://cdn.staticfile.org/quill/1.3.4/quill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js"></script>

到这里,我们的第三方依赖包(js)的CDN已经引入成功了,我们还需要继续引第三方样式(css)的依赖包.

需要注意的是,在引入CDN资源时,需要重视彼此之间的依赖关系和顺序,可能顺序不同,会导致不可预知的错误

    <!-- nprogress 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
    
    <!-- 富文本编辑器 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css" />
    

5.通过CDN优化ElementUI的打包

虽然在开发阶段,我们启用了element-ui组件的按需加载。尽可能的减小打包的体积,但是那些被按需加载的组件,还是占用了较大的文件体积。

image.png

此时,我们可以将element-ui中的组件,也通过CDN的形式来加载,这样能够进一步减小打包后的文件体积

image.png

具体操作流程:

1.在main-prod.js中,注释掉elemeng-ui按需加载的代码

2.在public/index.html的头部区域中,通过CDN加载element-ui的js和css样式

   <!-- element-ui 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css" />
    
   <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>

6.自定义首页内容

不同的打包环境下,首页内容可能会有所不同,我们可以通过插件的方式进行定制,插件配置如下:

首先,在vue.config.js中更新内容

chainWebpack: config => {
        // 发布模式
        config.when(process.env.NODE_ENV === 'production', config => {
         
            config.plugin('html').tap(args => {
                args[0].isProd = true
                return args
            })
        })

        // 开发模式
        config.when(process.env.NODE_ENV === 'development', config => {
         
            config.plugin('html').tap(args => {
                args[0].isProd = false
                return args
            })
        })
    }

然后,需要在public/index.html首页中,根据isProd的值,来决定如何渲染页面结构

//按需渲染页面的标题  <%= %>是模板字符串中的语法,也就是输出的意思
 <title><%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %>电商后台管理系统</title>
 
 //按需加载外部的CDN资源   <% %>是客户端用来获取服务端变量的代码,一般把html和服务器代码写在一起的时候,使用此种方式
 <% if(htmlWebpackPlugin.options.isProd){ %>
 
    <!-- nprogress 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
    <!-- 富文本编辑器 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css" />
    <!-- element-ui 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css" />

    <script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js"></script>
    <script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
    <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
    <!-- 富文本编辑器的 js 文件 -->
    <script src="https://cdn.staticfile.org/quill/1.3.4/quill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js"></script>

    <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>

 <% } %>

7.路由懒加载

当打包构建项目时,JavaScript包会变得非常大,影响页面加载,如果我们能把不同路由对应的组件飞分割成不同的代码快,然后路由被访问的时候才加载对应组件,这样就更加高效了

具体的实现需要三个步骤

1.安装@babel/plugin-syntax-dynamic-import,->>>npm install @babel/plugin-syntax-dynamic-import --save-dev,第七个版本

2.在babel.config.js配置文件中声明该插件

// 这是项目发布阶段需要用到的 babel 插件
const prodPlugins = []
if (process.env.NODE_ENV === 'production') {
  prodPlugins.push('transform-remove-console')
}

module.exports = {
  presets: ['@vue/app'],
  plugins: [
    [
      'component',
      {
        libraryName: 'element-ui',
        styleLibraryName: 'theme-chalk'
      }
    ],
    // 发布产品时候的插件数组
    ...prodPlugins,
    '@babel/plugin-syntax-dynamic-import'    (这里声明插件)
  ]
}

3.将路由改成按需加载的形式,示例代码如下:

有时候我们想把某个路由下的所有组件都打包在同个异步块 (chunk) 中。只需要使用命名 chunk,一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4):

webpack 会将任何一个异步模块与相同的块名称组合到相同的异步块中。

// import Login from './components/Login.vue'
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ './components/Login.vue')
// import Home from './components/Home.vue'
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ './components/Home.vue')
// import Welcome from './components/Welcome.vue'
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ './components/Welcome.vue')

// import Users from './components/user/Users.vue'
const Users = () => import(/* webpackChunkName: "Users_Rights_Roles" */ './components/user/Users.vue')
// import Rights from './components/power/Rights.vue'
const Rights = () => import(/* webpackChunkName: "Users_Rights_Roles" */ './components/power/Rights.vue')
// import Roles from './components/power/Roles.vue'
const Roles = () => import(/* webpackChunkName: "Users_Rights_Roles" */ './components/power/Roles.vue')


二、项目上线

1.通过node创建web服务器

关键词:expressappapp.use()app.listen()

const express = require('express')
const compression = require('compression')
const https = require('https')
const fs = require('fs')
const app = express()

//配置ssl证书
const options = {
  cert: fs.readFileSync('./full_chain.pem'),
  key: fs.readFileSync('./private.key')
}

// 一定要把这一行代码,写到 静态资源托管之前
app.use(compression())
app.use(express.static('./dist'))

app.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

//使用https协议
// https.createServer(options, app).listen(443)

2.开启gzip配置

使用gzip可以减小文件体积,使得传输都更快

可以通过服务器端使用Express做gzip压缩

//1.安装相应包
npm install compression -D

//2.导入包(必须保证在静态资源dist托管之前,才能生效)
const compression =require('compression');
//app.use(express.static('./dist'))

//3.启用中间件
app.use(compression())

3.配置https服务

为什么要启动HTTPS服务?

  • 传统的HTTP协议传输的数据都是明文,不安全,容易被窃取数据
  • 采用HTTPS协议对传输的数据进行了加密处理,可以防止数据被中间人窃取,使用更加安全

申请SSL证书(freessl.cn/

1.进入freessl.cn/ ,输入要申请的域名并选择品牌(多域名通配符)

2.输入自己的邮箱并选择相关选项

3.验证DNDS(在域名管理后台添加TXT记录)

4.验证通过后,下载SSL证书(full_chain.pen公钥 private.key私钥)

5.在后台项目中导入证书

const https = require('https')
const fs = require('fs')

//配置ssl证书
const options = {
  cert: fs.readFileSync('./full_chain.pem'),
  key: fs.readFileSync('./private.key')
}
//https协议的默认端口是443 http的默认端口是80
https.createServer(options, app).listen(443)

4.使用pm2管理应用

当我们把服务器终端关闭后,浏览器前端访问失败,如果利用pm2后,关闭服务器中断后,浏览器可以正常访问。

1.在服务器中安装pm2:npm i pm2 -g

2.启动项目:pm2 start(脚本) --name (自定义名称)

pm2 start .\app.js --name web_vueshop

3.查看运行项目:pm2 ls

4.重启项目:pm2 restart 自定义名称

pm2 restart web_vueshop

5.停止项目:pm2 stop自定义名称

pm2 stop web_vueshop

6.删除项目:pm2 delete 自定义名称