当前位置:网站首页>Project optimization + online (Master?)
Project optimization + online (Master?)
2022-06-22 09:19:00 【Jdoit CW】
The goal is
understand vue Optimization process of the project
To be able to web Project deployment to server
One . Optimize vue project
1. Generate packaged reports , Optimize the project according to the report
When the packaging , In order to intuitively find problems in the project , Reports can be generated at package time .
1.1 There are two ways to generate reports :
- Generate reports in the form of command line arguments
// adopt vue-cli Command options to generate packaged reports
// --report Options can generate report.html To help analyze package contentvue-cli-service build --report - By visualizing UI Panel view report directly ( recommend )
In the visual UI The palette , adoptConsole and analysis panel, You can easily see the problems in the project .
Example :

1.2 Handle the common warnings after packaging :
: For those left in the project console.log() sentence , A warning appears when packaging . If more , It is also relatively troublesome to remove , If removed manually , It cannot print normally during development , At this point, we can use the plug-in babel-plugin-transform-remove-console, It can be used in projects build Phase remove all console Information .
①: Open the project console , Click dependency -> Development depends on , Input babel-plugin-transform-remove-console, install
②: open babel.config.js, Edit the code as follows :
//# Project release phase needs to use bable plug-in unit
const prodPlugins = []
//# Determine whether it is in the production stage ( If it is , Add the plug-in to the array , Then use the expansion operator to expand the array )
if (process.env.NODE_ENV === 'production') {
prodPlugins.push('transform-remove-console')
}
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
],
//# The array of plug-ins used when releasing products
...prodPlugins,
//# Road load by lazy
'@babel/plugin-syntax-dynamic-import'
]
}
2. adopt vue.config.js modify webpack Default configuration
For the generated packaged report , Warning is : The resource exceeds the optimal limit size ( Too many resources ), If in the Production environment Resources must be optimized as much as possible , Thus increasing the efficiency of resource requests . But for the development environment , We don't pursue too much ( For the purpose of convenient development ).so, We want to The production environment and the development environment are configured separately .
: Development mode and release mode Specify different packaging entries
By default ,Vue Project development mode and release mode , Share the same packaged entry file ( namely src/main.js). In order to
The development process is separated from the release process , We can do two models , Each specifies the packaged entry file , namely :
① Development mode The entry file of is src/main-dev.js
② Release pattern The entry file of is src/main-prod.js
: adopt vue-cli 3.0 Tool generated projects , The default hides all webpack Configuration item for , The purpose is to Configuration process of shielding items , Give way to Cheng
The foreman put the focus of his work , On the implementation of specific functions and business logic .
If programmers have modify webpack Default configuration requirements , It can be in the project root directory in , On demand establish vue.config.js This configuration file , from
For the project Make customized configuration during the packaging and publishing process ( More configuration reference : https://cli.vuejs.org/zh/config/#vue-config-js).
module.exports = {
chainWebpack: config => {
//# Production environment
config.when(process.env.NODE_ENV === 'production', config => {
// Configure the production environment packaging portal
config.entry('app').clear().add('./src/main-prod.js')
})
//# development environment
config.when(process.env.NODE_ENV === 'development', config => {
// Configure the development environment packaging portal
config.entry('app').clear().add('./src/main-dev.js')
})
}
}
3. adopt externals Load external CDN resources ( Third party library enabled CDN)
By default , adopt import Syntax imported Third party dependency package , Will eventually be Package and merge To the same file , This leads to a successful packaging
after , single Too large file size The problem of .
: In order to solve the above problems , Can pass webpack Of externals node , To configure and load external CDN resources . All statements are made in externals Third party dependency package in , They won't be packed .
①: stay vue.config.js Medium Production environment Write what needs to be loaded external CDN resources
config.set('externals', {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
lodash: '_',
echarts: 'echarts',
nprogress: 'NProgress',
'vue-quill-editor': 'VueQuillEditor'
})
②: meanwhile , Need to be in public/index.html The head of the document , add to CDN Resource Citation ( Here to nprogress For example ):
<!-- nprogress Style sheet file -->
<link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
<!-- nprogress Of js file -->
<script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
Be careful : Resources css The document should be in js The document was introduced before
4. Element-UI Components load on demand
: Although in the development phase , Enable element-ui On demand loading of components , Can reduce as much as possible Packed volume , But those are added on demand
Loaded components , still It takes up a large file volume . here , We can element-ui Components in , also adopt CDN In the form of Lega
load , This will help Further reduce the volume of packaged files .
① : stay main-prod.js in , Comment out element-ui Code loaded on demand
② : stay index.html In the head area of , adopt CDN load element-ui Of js and css style
<!-- element-ui Style sheet file -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" />
<!-- element-ui Of js file -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
After the above one meal operation , The volume of the project after packaging is the compliance rate 
5. Road load by lazy
Although the volume of the file is qualified , But the loading speed is still worth optimizing , For routing , We should adopt : Road load by lazy ( Import on demand ) The way , Use reload , Avoid unprovoked loading .
: When When packaging build projects ,JavaScript The bag will get very big , Affects page loading . If we can put Components corresponding to different routes are divided into Different code blocks , then The corresponding component is loaded only when the route is accessed , So you More efficient 了 . Learn about route lazy loading :https://router.vuejs.org/zh/guide/advanced/lazy-loading.html
① : install @babel/plugin-syntax-dynamic-import package .
② : stay babel.config.js The plug-in is declared in the configuration file ( The above file already has a declaration method ).
③ : take The route is changed to the form of on-demand loading , The sample code is as follows :
const Login = () => import ( /* webpackChunkName: "Login_Home_Welcome" */ '../components/Login.vue')
const Home = () => import ( /* webpackChunkName: "Login_Home_Welcome" */ '../components/Home.vue')
const Welcome = () => import ( /* webpackChunkName: "Login_Home_Welcome" */ '../components/Welcome.vue')
Be careful : Here put Login/Home/Welcome Divided into one group , When accessing any of these components , Will load other components ( Grouping depends on the project )
6. Home page content customization
Different packaging environments , The content of the home page may be different . We can customize it through plug-ins .
module.exports = {
chainWebpack: config => {
//# Release pattern
config.when(process.env.NODE_ENV === 'production', config => {
config.plugin('html').tap(args => {
args[0].isProd = true
return args
})
})
//# Development mode
config.when(process.env.NODE_ENV === 'development', config => {
config.plugin('html').tap(args => {
args[0].isProd = false
return args
})
})
}
}
stay public/index.html Home page , According to isProd Value , To decide how to render the page structure
<!– Render the title of the page on demand --> <title><%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %> my app</title> <!– Load external... On demand CDN resources --> <% if(htmlWebpackPlugin.options.isProd) {
%>
<!— adopt externals The external part of the load CDN resources -->
<% } %>
Be careful : The original grammar is used here template engine
Two . Deployment project
1. adopt node Create a server
establish node project , And install express, adopt express Quick creation web The server , take vue It's packaged dist Folder ,
It can be managed as a static resource ( Note that all items can , Here is vue project )
const express = require('express')
const app = express()
app.use(express.static('./dist'))
app.listen(80, () => {
console.log(' Server startup , Please visit :http://127.0.0.1')
})
2. Turn on gzip Compress
Use gzip Can reduce file size , Make transmission faster .
: It can be used on the server side Express do gzip Compress
①: Install the corresponding package :npm install compression
②: Import package , And set up
const compression = require('compression')
//# Write before statically managed resources
app.use(compression())
Before and after compression :

File transfer sizes differ significantly
3. To configure https service
: Enable https Reasons for service :
①: Conventional HTTP agreement The data transmitted is Plaintext , unsafe
②: use HTTPS agreement For transmission The data is encrypted , It can prevent data from being stolen by middlemen , Use more Security
: To configure https service
① : Get into https://freessl.cn/ Official website , Enter the domain name you want to apply for and select the brand .
② : Enter your email and select the relevant options .
③ : verification DNS( Add in domain name management background TXT Record ).
④ : After passing the verification , download SSL certificate ( full_chain.pem Public key ;private.key Private key ).
⑤ : Import Certificate in background project .
const https = require('https');
const fs = require('fs');
const options = {
cert: fs.readFileSync('./full_chain.pem'),
key: fs.readFileSync('./private.key')
}
https.createServer(options, app).listen(443);
Be careful :https Default port number 443, This operation is usually developed by back-end engineers .
4. Use pm2 Management applications
about node Set up the server , Once the terminal window is closed , The server stops running . can pm2 This problem can be well solved , use pm2 After managing the server , The terminal can be shut down at will , The server still accesses normally . secondly pm2 And server records , It is convenient for us to manage them
:pm2 Operation command :
① : Install... In the server pm2:npm i pm2 -g
② : Start project :pm2 start Script --name Custom name
③ : View the running project :pm2 ls
④ : Restart project :pm2 restart Custom name ( But id)
⑤ : Stop the project :pm2 stop Custom name
⑥ : Delete the project :pm2 delete Custom name
Some examples :


Be careful :id Can also be operated by pm2 Application of management
Last : well , Come on together , Common progress
边栏推荐
猜你喜欢

Logistic regression and linear regression
![[network security officer] an attack technology that needs to be understood - high hidden and high persistent threats](/img/c9/c0ee95e816cac698f5397cc369d9ec.jpg)
[network security officer] an attack technology that needs to be understood - high hidden and high persistent threats

字符串与内存操作函数详解与模拟实现

Detailed explanation and Simulation of string and memory operation functions

模板引擎,让交互变得优雅

Solidity from introduction to practice (6)

When easypoi imports the secondary header data of an excel file, the data in the first column of the @excelentity entity class is null

锁-ReentrantLock

VMware installation Kali

VMware安装Kali
随机推荐
Kali Trojan invades win7 system
Machine learning | nltk_ Data download error |nltk's stopwords corpus download error solution
两个线程各执行100次i++,得到的可能值
mknod
STM32 crashes when upgrading bootloader to jump app Online
Stream stream creation_ Operation_ Collection_ case
pytorch的模块使用:线性模型(未完成)
There are three ways to traverse the map. Second, you know
Php+sql get the field name and detailed attributes of MySQL data table
Pytorch oserror: DLL load failed: problem solving
IS_ ERR()
Threejs implementation of simple panoramic view demo
Typical cases of final
Performance optimization topics
Embedded development terminology concept summary
Brush questions in C language | output love (14) with putchar
OpenCV每日函数 直方图相关(3)
集合中的类--->你关注过那些是线程安全的吗?
经典&&案例
【node】node+短信api 实现验证码登录