current position:Home>Vue - 11 - webpack nanny level tutorial 02 - source map, oneof, externals, tree shaking technology, installing jQuery, packaging and compressing CSS, and code split
Vue - 11 - webpack nanny level tutorial 02 - source map, oneof, externals, tree shaking technology, installing jQuery, packaging and compressing CSS, and code split
2022-01-27 01:26:43 【Nanchen_ forty-two】
Catalog
3、 ... and 、 install jQuery Plug in and jQuery package
5、 ... and 、 Yes css Package and compress the file
6、 ... and 、webpack performance optimization -tree shaking( Trees shake )
2、 Turn on **production** Environmental Science
7、 ... and 、code split( The code segment )
The first method : Multi entry split
The second method :optimization
The third method :import Dynamic import Syntax
One 、source-map
source-map Error checking
To configure sourve-map Configure before css Compatibility writing
source-map: One provides Mapping of source code to post build code Technology ( If the code goes wrong after the build , Source code errors can be traced by mapping )
Use the examples in the previous chapter to demonstrate : Please refer to webpack Package nanny tutorial 01
stay webpack.config.js Add devtool:'source-map'
devtool: 'eval-source-map'
Added two troubleshooting files map
Two 、oneOf
Speed up packing , hold rules All the contents in it are {oneOf:[]}
Run again
npx webpack-dev-server
3、 ... and 、 install jQuery Plug in and jQuery package
npm install jquery --save-dev
introduce jQuery:
import $ from 'jquery';
console.log($);
package :
stay node_moddules Found already in the folder jQuery That is success
Run it :
npx webpack-dev-server
But if you introduce too many files, such as charts unitApp Waiting for a series of documents will lead to main.js Particularly large , The opening speed will also slow down . It needs to be solved at this time
Four 、externals
externals: Let some libraries not be packaged .
webpack.config.js Middle configuration : Delete the comments when using
externals: {
// Refuse jQuery Packed in ( adopt cdn introduce , It will be faster )
// Ignored library name -- npm Package name
jquery: 'jQuery'
}
Then it needs to be in index.html Pass through cdn To introduce :
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
introduce jquery.js The library can use cat cloud to get the path
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Can pass npx webpack-dev-server To run and view the size
Before compression :main.js by 555kib
After the compression :main.js by 273kib
5、 ... and 、 Yes css Package and compress the file
npm install css-minimizer-webpack-plugin --save-dev
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");// Compress css
new CssMinimizerPlugin(),// New compression css Method
Just pack it
6、 ... and 、webpack performance optimization -tree shaking( Trees shake )
tree shaking: Remove useless code not used in the application
Premise :
1、 Use ES6 modularization
You can use import,export. require Can not be
2、 Turn on **production** Environmental Science
This will automatically remove the useless code
effect : Reduce code size
If js Introduce add, No introduction mul. But it's all packed in , It shows that there is a problem here
resolvent : Remove useless code by shaking the tree
Back to the editor , stay mathUtils.js Code before comments in
Write separately ES6 grammar
export function add(num1,num2){
return num1 + num2
}
export function mul(num1,num2){
return num1 * num2
}
If this is development
process.env.NODE_ENV = 'developent'
Let's pack it here. Can we pack it out
You can see that the package has been successfully completed , But I just want to introduce add, I don't want to introduce mul. You need to introduce... Through tree shaking
hold mode Switch to production
Pack it up , You can see that there is mul
Note here mul
Pack again , You will find that you can't find mul 了
And it will automatically clear your comments
stay package.json Middle configuration :
"sideEffects": false Indicates that all code has no side effects ( All can be done tree shaking)
This can lead to problems : May put css / @babel/polyfill File crowding out ( side effect )
So it can be configured "sideEffects": ["*.css", "*.less"]: It won't be right css/less file tree shaking Handle
7、 ... and 、code split( The code segment )
Why use code segmentation ?
stay vue Single page application , If nothing is done , all vue The file will be packaged as a file , This file is very large , It causes the web page to enter slowly for the first time . After code segmentation , Will separate the code into different bundle in , Then load these files on demand , It can improve the speed of the first entry of the page , Website performance can also be improved .
As the application expands , package (bunle) It gets bigger and bigger . Especially if a huge third-party library is introduced . You must pay attention to the size of the package you introduce . Prevent you from packing ,app Loading takes too long .
To prevent a big bag from coming out , Code segmentation is a better solution . Code segmentation is Webpack and Browserify( adopt factor-bundle) A feature of . Allow to create multiple packages , And then at run time (runtime) load .
Code segmentation can help App Realization 『 Lazy loading 』 The part that the current user needs , You don't have to load all . In this way, dynamic loading can improve application performance .
In short, it is to put a js Split into multiple small js Then run at the same time , Similar to asynchronous operation
The first method : Multi entry split
hold mathUitls.js Put the name in its webpack.config.js In the entry file of :
entry: {
index: './src/index.js',
mathUtils: './src/mathUtils.js'
},
output: {
// [name]: Take file name
filename: 'js/[name].[contenthash:10].js',
path: path.resolve(__dirname, 'dist')
},
After packing, it can be separated
The second method :optimization
optimization: {
splitChunks: {
chunks: 'all'
}
},
all: Take everything apart
!!! Be careful :
Because usually only one entry file will be introduced into the project .
So you can pack
output.filename
The output file name of is[name].min.js
,[name]
according toentry
The configuration of is inferred asindex
, So the output isindex.min.js
;
The third method :import Dynamic import Syntax
If it is ordinary packaging, it will mathUtils.js Package files to index.js In the document
So we can use dynamic import syntax to export it separately
import('./mathUtils').then(({add,mul})=>{
console.log(add(300,200));
}).catch(()=>{
console.log(' File load failed ');
})
Pack again
But here you will find that just looking at the name can't tell which is right and which
So add a comment webpackChunkName
/*webpackChunkName:'mathUtils'*/
webpackChunkName: Appoint test Name of the file packaged separately
import(/*webpackChunkName:'mathUtils'*/'./mathUtils').then(({add,mul})=>{
console.log(add(300,200));
}).catch(()=>{
console.log(' File load failed ');
})
Pack again npm run build
You can see that the name has been changed
copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270126404287.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command