Summarize and organize the optimization scheme involved in the front-end work
One, lazy loading
1. Lazy loading concept
Lazy loading, also known as lazy loading, on-demand loading, refers to the delayed loading of a large amount of picture data in a web page, is a better way to optimize web performance. When we use a large number of pictures in a page, if we load them all at once when loading for the first time, when the network is poor, the picture loading is slow or the loading fails, whether it will cause bad user experience?
Using image lazy loading can solve the above problems. Images outside the visual area are not loaded until the screen is rolled, but as the screen is rolled into the visual area, the image is loaded. This makes web pages load faster and reduces the load on the server.
2. Lazy loading characteristics
- Reduce invalid resource loading: Using lazy loading significantly reduces server stress and traffic, as well as browser load.
- Improve user experience: If you load more images at the same time, you may need to wait for a long time, which affects user experience. Lazy loading can greatly improve user experience.
- Prevent loading too many images and affecting the loading of other resource files: it will affect the normal use of the website.
3. The implementation principle of lazy loading
The loading of the image is triggered by the SRC attribute, and when the SRC attribute is assigned, the browser sends an HTTP request for the image resource. According to this principle, we can use the DATA-xxx attribute of HTML5 to store the path of the image. When the image needs to be loaded, the path of the image in data-xxx is assigned to SRC, so as to realize the on-demand loading of the image, that is, lazy loading.
Note: XXX in data-xxx can be customized, so we use data-src to define it
The lazy loading implementation focuses on determining which images the user needs to load. In the browser, the resources in the visual area are the resources the user needs. So when the image appears in the visible area, get the real address of the image and assign it to the image.
There are two ways to implement lazy loading:
1. Lazy loading with native JavaScript:
[ 知识点: ]
(1) Window. innerHeight is the height of the browser’s viewable area.
(2) document. Body. ScrollTop | | document. The documentElement. ScrollTop is the distance between the browser scroll
(3) imgs.offsetTop is the height of the top of the element from the top of the document (including the distance of the scroll bar)
[Illustration:]
[ code: ]
<div class="container"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> </div> <script setup> const imgs = document.querySelectorAll('img'); function lozyLoad(){ const scrollTop = document.body.scrollTop || document.documentElement.scrollTop; const winHeight= window.innerHeight; for(let i=0; i < imgs.length; i++){ if(imgs[i].offsetTop < scrollTop + winHeight ){ imgs[i].src = imgs[i].getAttribute('data-src'); } } } window.onscroll = lozyLoad; </script>Copy the code
2. IntersectionObserver attribute is used to achieve:
[Trigger condition:]
- Executed whenever the target element intersects with the device view or other elements. The device window or any other element is called the root element or root.
- The first time the Observer listens on the target element.
[Conditions of use:]
- Image lazy loading – images are loaded only when they are scrolled into view.
- Content infinite scrolling – that is, when the user scrolls near the bottom of the content, more is loaded directly, without the user having to turn the page, giving the user the illusion that the web page can scroll indefinitely.
- Detect AD exposure – In order to calculate AD revenue, you need to know the exposure of AD elements.
- Perform a task or play an animation when the user sees an area.
[ code: ]
<div class="container">
<img style="height:1080px;" data-src="./png1.png" />
<img style="height:1080px;" data-src="./png2.png" />
<img style="height:1080px;" data-src="./png3.png" />
<img style="height:1080px;" data-src="./png4.png" />
<img style="height:1080px;" data-src="./png5.png" />
<img style="height:1080px;" data-src="./png6.png" />
</div>
<script>
const imgs = document.querySelectorAll("img");
const observe = new IntersectionObserver((observes) = > {
observes.forEach((ele) = > {
// If isIntersecting is true, then the element enters the visualization area
if (ele.isIntersecting) {
//do something...
ele.target.src = ele.target.dataset.src;
observe.unobserve(ele.target); // Cancel the listener}}); });// After creating observe, specify a target element to observe:
imgs.forEach((el) = > {
observe.observe(el);
});
</script>
Copy the code
4. The difference between lazy loading and preloading
Both methods are ways to improve page performance, the main difference between the two is: one for early loading, one for slow loading or even no loading. Lazy loading relieves the server pressure to some extent, while preloading increases the server pressure.
- Lazy loading: Load the site when the user needs to access it, which can improve the loading speed of the first screen of the site, improve user experience, and reduce the pressure on the server. It works for sites with lots of images and long pages.
- Preload: Loads the required resources locally in advance so they can be fetched directly from the cache when they are needed later. Preloading can reduce user waiting time and improve user experience. It is suitable for large video or image scenarios.
Reflux and redrawing
1. Concepts and trigger conditions of backflow and redrawing
(1) the backflow
The process by which the browser rerenders part or all of the document when the size, structure, or attributes of some or all of the elements in the rendering tree change is called backflow. The following operations all cause backflow:
- The first rendering of the page
- The browser window size changed. Procedure
- The content of the element changes
- The size or position of the element changes
- The font size of the element changes
- Enable CSS pseudo-classes
- Query some properties or call some methods
- Add or remove visible DOM elements
Since the browser renders the page based on a streaming layout, when backflow is triggered, it causes the surrounding DOM elements to be rearranged in two ways:
- Global scope: Rearrange the entire render tree, starting at the root node
- Local scope: Rearrange a part of the render tree or a render object node
(2) redrawn
When the style of some element on the page changes without affecting its position in the document flow, the browser redraws the element, a process known as redrawing. The following operations cause a redraw:
- Color, background related attributes: background-color, background-image, etc
- Outline properties: outline-color, outline-width, text-decoration
- Border-radius, Visivility, box-shadow
Note: Redraw is always triggered when backflow is triggered, but redraw does not necessarily trigger backflow.
2. How to avoid backflow and redrawing?
Measures to reduce backflow and redraw:
- When manipulating the DOM, try to operate on low-level DOM nodes
- Do not use the table layout, a small change may cause the entire table to be rearranged
- Do not use CSS expressions
- Do not manipulate the style of the element too often. For static pages, change the class name, not the style
- Use absolute or fixed to remove elements from the document flow so that their changes do not affect other elements
- To avoid frequent DOM manipulation, you can create a documentFragment, apply all DOM operations to it, and finally add them to the document once
- Set the element to display: None and display it at the end. Because DOM operations on elements with the display attribute none do not cause backflow and redraw
- Multiple reads (or writes) of the DOM are grouped together, rather than the reads and writes interspersed with the writes. This is thanks to the browser’s render queue mechanism
The browser has its own optimized ———— render queue for backflow and redrawing of pages
The browser puts all the backflow and redraw operations in a queue, and when the number of operations in the queue reaches a certain number of times, the browser batches the queue. This will turn multiple backflow and redraw into a single backflow redraw.
Above, putting multiple reads (or writes) together will wait until all reads are queued, so instead of firing multiple times, backflow will only fire once.
3. How to optimize animation?
As for how to optimize the animation, we know that in general, the animation requires frequent DOM manipulation, which will lead to page performance problems. We can set the position property of the animation to absolute or fixed to remove the animation from the document flow, so that its backflow will not affect the page.
4. What is a documentFragment? What’s the difference between using it and manipulating the DOM directly?
DocumentFragment in MDN
DocumentFragment interface, a minimal document object with no parent object. It is used as a lightweight version of Document that stores a Document structure composed of nodes, just like a standard Document. Compared with Document, the biggest difference is that DocumentFragment is not part of the real DOM tree, and its change will not trigger the DOM tree re-rendering, and will not cause performance problems.
When we insert a DocumentFragment node into a document tree, we insert not the DocumentFragment itself, but all of its descendants. In the case of frequent DOM operations, we can insert DOM elements into the DocumentFragment and then insert all descendants into the document at once. Inserting the DocumentFragment node into the DOM tree does not trigger page redrawing, which greatly improves page performance compared to manipulating the DOM directly.
Three, throttling and anti – shake
1. Understanding of throttling and shaking prevention
- Anti – shake: when the function is continuously triggered, it will trigger once after a certain period of time.
- Throttling: Fires at regular intervals while continuously firing functions.
Application scenarios of anti-shake function:
- Button submission scenario: To prevent multiple submissions, only one execution is performed.
- Input query scenario: To prevent consecutive input requests, only the last consecutive input is executed.
Throttling function usage scenarios:
- Drag scenario: Perform this operation only once at a fixed time to prevent uHF position changes.
- Scrolling scenario: Monitor browser resize.
- Animated scenes: Avoid performance issues caused by multiple animations in a short period of time.
2. Implement the throttling function and anti-shake function
Stabilization:
function debounce(fn, wait) { var timer = null; return function() { var context = this, args = [...arguments]; If (timer) {clearTimeout(timer); if (timer) {clearTimeout(timer); timer = null; } // Set the timer so that the event interval specified after the timer = setTimeout(() => {fn.apply(context, args); }, wait); }; }Copy the code
Throttling:
Function throttle(fn, delay) {var preTime = date.now (); return function() { var context = this, args = [...arguments], nowTime = Date.now(); // If the interval exceeds the specified time, the function is executed. if (nowTime - preTime >= delay) { preTime = Date.now(); return fn.apply(context, args); }}; } // function throttle (fun, wait){ let timeout = null return function(){ let context = this let args = [...arguments] if(! timeout){ timeout = setTimeout(() => { fun.apply(context, args) timeout = null }, wait) } } }Copy the code
4. Picture optimization
1. Commonly used picture optimization skills in daily projects
- No pictures (hh, no pictures, no optimization). A lot of time to use some of the image modification class, can be solved with CSS without pictures!!
- For the mobile end, the screen width is small, there is no need to request the original image waste broadband. Images are all CDN (CDN is to distribute the content of the source station to the node closest to the user, so that the user can obtain the required content nearby, and improve the response speed and success rate of user access. Solve the problem of access delay caused by distribution, bandwidth, server performance, suitable for site acceleration, on-demand, live and other scenarios. Load, you can calculate the width of the screen, and then request the corresponding cropped image.
- The miniatures use base64 format.
- Multiple icon files can be merged into Sprite images.
- Choose the correct image format.
- Use WebP for browsers that can display WebP. Because WebP format has excellent image data compression algorithm, can bring smaller picture volume and naked eye recognition quality, the disadvantage is compatibility.
- PNG is used for small images, but for most ICONS, SVG can be used instead.
- Use JPEG for photos.
2. Common picture formats and usage scenarios
Index color: To save storage, map the colors used in the image to a color table. Index colors are usually 16, 32, 64, 128 or 256 colors, but not more than 256 colors. Direct color: Each pixel value is divided into R, G, and B components, and each component is transformed as a separate index value. That is, through the corresponding color transformation table to find out the intensity of the primary color, with the transformation of R, G, B intensity value generated by the color is called the direct color. It is characterized by the transformation of each primary color.
- BMP: a lossless bitmap that supports both index and direct colors. This image format does little to compress the data, so the BMP format is relatively large.
- GIF: is a lossless, indexed color bitmap. LZW compression algorithm is used for coding. Small file, is the advantage of GIF format, at the same time, GIF format also has the advantages of supporting animation and transparency. However, GIF format only supports 8bit index color, so GIF format is suitable for the color requirements are not high and require a small file size scene.
- JPEG: lossy, direct color bitmap. JPEG image advantage is the use of direct color, thanks to the richer color, JPEG is very suitable for storing pictures, compared with GIF, JPEG is not suitable for storing corporate Logo, wireframes of the type of pictures. Lossy compression can cause the image to be blurred, and the choice of direct colors can cause the image file to be larger than GIF.
- Png-8: is a lossless, indexed color bitmap. PNG is a relatively new image format, and PNG-8 is a very good alternative to GIF. When possible, use PNG-8 instead of GIF because pNG-8 has a smaller file size for the same image effect. In addition, pNG-8 also supports transparency adjustment, which GIF does not. Unless animation support is required, there is no reason to use GIF instead of PNG-8.
- Png-24: is a lossless, direct color histogram. The advantage of PNG-24 is that it compresses the image data, resulting in a much smaller file size than BMP for the same effect. Of course, pNG-24 images are still better than JPEG, GIF, pnG-8 images.
- SVG: lossless vector graphics. The fact that SVG is a vector diagram means that SVG images consist of lines and curves and methods for drawing them. When you zoom in on an SVG image, you still see lines and curves, not pixels. This means that SVG images do not distort when enlarged, so it is suitable for drawing logos, ICONS, etc.
- WebP: is a new image format developed by Google. WebP is a direct color bitmap that supports both lossy and lossless compression. As the name suggests, it was born for the Web. Why? That is to say, the same quality image, WebP format has a smaller file size. Web sites are now full of images, and if you can reduce the file size of each image, you can greatly reduce the amount of data transferred between the browser and the server, thus reducing access latency and improving the experience. Currently, only Chrome and Opera support WebP, which is not very compatible.
- With lossless compression, a WebP image of the same quality is 26% smaller than a PNG file.
- WebP images with the same image accuracy are 25% to 34% smaller than JPEG files under lossy compression.
- The WebP image format supports image transparency, a lossless compression of WebP images that requires only 22% of the additional file size to support transparency.
Five, Webpack optimization
1. How to improve the packaging speed of Webpack
(1) Optimize Loader
For Loader, the impact of packaging efficiency must be one of the Babel. Because Babel converts code to strings to generate an AST, and then transforms the AST to generate new code, the bigger the project, the more code it transforms, the less efficient it is. Of course, this can be optimized. First we optimize the Loader file search scope
Module. exports = {module: {rules: [{// js file Babel test: /\.js$/, loader: // include: [resolve(' SRC ')] // exclude: /node_modules/}]}}Copy the code
For Babel, you want only JS code, and then node_modules code is compiled, so there’s no need to process it again. Of course, this is not enough. You can also cache Babel’s compiled files and compile only the changed code files next time, which can greatly speed up the packaging time.
loader: 'babel-loader? cacheDirectory=true'Copy the code
(2) HappyPack
Due to the fact that Node is single-threaded, Webpack is also single-threaded during packaging, especially during Loader execution, which leads to a waiting situation.
HappyPack can convert Loader synchronous execution to parallel, which makes full use of system resources to speed up packaging
Module: {loaders: [{test: /\.js$/, include: [resolve(' SRC ')], exclude: /node_modules/, // id: loaders: [{test: /\.js$/, include: [resolve(' SRC ')], exclude: /node_modules/, // id 'happypack/loader?id=happybabel' } ] }, plugins: [ new HappyPack({ id: 'happybabel', loaders: ['babel-loader? CacheDirectory '], // Enable 4 threads: 4})]Copy the code
(3) the DllPlugin
DllPlugin can pre-package and import specific class libraries. This approach greatly reduces the number of times that libraries need to be repackaged only when they are updated, and also optimizes the separation of common code into separate files. The DllPlugin can be used as follows:
// Exports = {entry: const path = require('path') const webpack = require('webpack') module.exports = {entry: Vendor: ['vue']}, output: {path: path.join(__dirname, 'dist'), filename: '[name].dl.js ', library: '[name]-[hash]'}, plugins: [new webpack.dllplugin ({// name must be the same as output.library) '[name]-[hash]', // This attribute needs to be consistent with the DllReferencePlugin context: __dirname, path: path.join(__dirname, 'dist', '[name]-manifest.json') }) ] }Copy the code
This configuration file then needs to be executed to generate the dependency files, which need to be introduced into the project using the DllReferencePlugin
// webpack.conf.js module.exports = { // ... Omit other configure plugins: [new webpack DllReferencePlugin ({context: __dirname, / / that the manifest before packaging json file manifest: require('./dist/vendor-manifest.json'), }) ] }Copy the code
(4) Code compression
In Webpack3, UglifyJS is generally used to compress the code, but this is run in a single thread. In order to speed up efficiency, webpack-parallel-Uglify-plugin can be used to run UglifyJS in parallel, thus improving efficiency.
In Webpack4, you don’t need to do this anymore, just set mode to production to enable this function by default. Code compression is also a performance optimization we must do, of course we can compress not only JS code, but also HTML, CSS code, and in the process of compressing JS code, we can also configure to delete console.log code such as functions.
(5) Others
You can speed up packaging with small optimization points
resolve.extensions
: indicates a list of file suffixes, in the default search order['.js', '.json']
If your imported files are not suffixed, the files will be looked up in this order. The list should be as short as possible, and the most frequent suffixes should be placed firstresolve.alias
: You can alias a path to make it easier for Webpack to find the pathmodule.noParse
: If you are sure that there are no other dependencies under a file, you can use this property to keep Webpack from scanning the file, which is useful for large libraries
2. How to usewebpackTo optimize front-end performance
Optimizing front-end performance with WebPack means optimizing the output of WebPack so that the packaged end result runs quickly and efficiently in the browser.
- Compress code: Remove unnecessary code, comments, simplify code writing, etc. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize to compress CSS
- Leverage CDN acceleration: During the build process, modify the referenced static resource path to the corresponding path on the CDN. The resource path can be modified using the Webpack for the output parameter and the publicPath parameter of each loader
- Tree Shaking: Remove pieces of code that never walk. This can be done by appending the parameter optimize-minimize when starting the Webpack
- Code Splitting: Splitting Code into chunks by routing dimension or component so it can be loaded on demand and take full advantage of the browser cache
- Extract common third-party libraries: The SplitChunksPlugin plug-in is used for common module extraction, using the browser cache to cache common code for long periods of time without frequent changes
Vi. Vue3 project packaging optimization configuration
In the Vue3 project, the webpack directory structure is gone and replaced with vue.config.js(built in the root directory!). .
1. The sourcemAP file does not need to be generated after packaging
module.exports={
productionSourceMap:false
}
Copy the code
2. Image compression
After vue is packed normally, some image files are very large, which makes the packing volume very large. Image-webpack-loader plug-in is used to compress large images to reduce the packing volume
NPM I image-webpack-loader –save-dev (2
module.exports={ productionSourceMap:false, ChainWebpack: config = > {/ / = = = = = = = = = compressed images start. = = = = = = = = config module. The rule (' images'). The use (' image - webpack - loader) . Loader (' image - webpack - loader '). The options ({bypassOnDebug: true}.) the end () / / = = = = = = = = = compressed images end = = = = = = = =}}Copy the code
3. (Optional) CDN Configuration
(1) Write at the top of vue.config.js
// Whether it is a production environment const isProduction = process.env.node_env! Const devNeedCdn = false const CDN = {// CDN: Externals: {vue: 'vue ', vuex: 'vuex ', 'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN link js: [' https://unpkg.com/vue@next ', 'https://cdn.staticfile.org/vuex/3.1.0/vuex.min.js', 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js']}Copy the code
Exports chainWebpack: exports chainWebpack: exports chainWebpack: exports chainWebpack: exports chainWebpack: exports chainWebpack: exports chainWebpack
/ / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin (' HTML '). The tap (args = > {/ / production environment or the local need CDN, To infuse the CDN the if (isProduction | | devNeedCdn) args [0]. The CDN = CDN return args}) / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = =Copy the code
Exports configureWebpack to vue.config.js module. Exports configureWebpack
ConfigureWebpack: config = > {/ / introduced in CDN way, to ignore the related resources to build the if (isProduction | | devNeedCdn) config. The externals = CDN. Externals}Copy the code
(4) The currently configured vue.config.js
// Whether it is a production environment const isProduction = process.env.node_env! Const devNeedCdn = false const CDN = {// CDN: Externals: {vue: 'vue ', vuex: 'vuex ', 'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN link js: [' https://unpkg.com/vue@next ', 'https://cdn.staticfile.org/vuex/3.1.0/vuex.min.js', 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js']} module. Exports = {productionSourceMap: false, chainWebpack: Config = > {/ / = = = = = = = = = = = = compressed images start = = = = = = = = = = = = config. The module. The rule (' images'). The use (' image - webpack - loader) .loader('image-webpack-loader') .options({ bypassOnDebug: True}). The end () / / = = = = = = = = = = = = compressed images end = = = = = = = = = = = = / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin (' HTML '). The tap (args If the CDN is required in the production environment or locally, To infuse the CDN the if (isProduction | | devNeedCdn) args [0]. The CDN = CDN return args}) / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = =}, configureWebpack: Config = > {/ / CDN way introduction, is to ignore the related resources to build the if (isProduction | | devNeedCdn) config. The externals = CDN. Externals}}Copy the code
(5) Write to public index.html
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> <link rel="icon" href="<%= BASE_URL %>favicon.ico" /> <! - use the CDN CSS file - > < % for (I in htmlWebpackPlugin var. The options. The CDN && htmlWebpackPlugin. Options. The CDN. CSS) {% > < link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet" /> <% } %> <! </title> </head> <body> <noscript> <strong >We're sorry but cli3_base doesn't work properly without JavaScript enabled. Please enable it to continue.</strong > </noscript> <div id="app"></div> <! - use the CDN JS file - > < % for (I in htmlWebpackPlugin var. The options. The CDN && htmlWebpackPlugin. Options. The CDN. JS) {% > < script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script> <% } %> <! -- use CDN JS file --> <! -- built files will be auto injected --> </body> </html>Copy the code
(6) Restart the project NPM run serve (7) in SRC /router.js will be modified
Vue.use(Router)
Copy the code
Instead of
if (! window.VueRouter) Vue.use(Router)Copy the code
(8) Restart NPM Run serve. The current configuration is the development environment, which cannot be seen in the Network JS of the browser. If you want to view it, please view it in vue.config.js
// Whether the local environment requires CDN const devNeedCdn = falseCopy the code
Instead of
// Whether the local environment requires CDN const devNeedCdn = trueCopy the code
Seven, code compression
(1) Install dependencies: NPM i-d uglifyjs-webpack-plugin (2) import files in the vue.config.js header
// const UglifyJsPlugin=require('uglifyjs-webpack-plugin');Copy the code
Exports configureWebpack added in vue.config.js module. Exports configureWebpack
If (isProduction) {config.plugins.push(new UglifyJsPlugin({uglifyOptions: Drop_debugger: true, drop_console: true, pure_funcs: ['console.log'] } }, sourceMap: false, parallel: true }) ) }Copy the code
8. Enable Gzip
(1) Install dependencies: NPM I –save-dev [email protected] (2) introduce dependencies at the top of vue.config.js
//gzip const CompressionWebpackPlugin=require('compression-webpack-plugin')Copy the code
Exports module. Exports configureWebpack (var. Config.js
/ / production related configure if (isProduction) {/ / code compression / /... // gzip const productionGzipExtensions = [' HTML ', 'js', 'css'] config.plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: New RegExp (' \. (' + productionGzipExtensions. Join (' | ') + ') $'), the threshold: 10240, / / only the size is larger than the value of resources will be processed 10240 minRatio: 0.8, // Only assets with compression ratio less than this value are processed deleteOriginalAssets: false}))}Copy the code
Nine, the common code is removed
Exports module. Exports configureWebpack. Exports module. Exports configureWebpack
Optimization = {splitChunks: {cacheGroups: {vendor: {chunks: 'all', test: /node_modules/, name: 'vendor', minChunks: 1, maxInitialRequests: 5, minSize: 0, priority: 100 }, common: { chunks: 'all', test: /[\/]src[\/]js[\/]/, name: 'common', minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 60 }, styles: { name: 'styles', test: /.(sa|sc|c)ss$/, chunks: 'all', enforce: true }, runtimeChunk: { name: 'manifest' } } } }Copy the code
Finally, the completed vue.config.js is served
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // gzip const CompressionWebpackPlugin = Require ('compression-webpack-plugin') const isProduction = process.env.node_env! Const devNeedCdn = true const CDN = {// CDN: Externals: {vue: 'vue ', vuex: 'vuex ', 'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN link js: [' https://unpkg.com/vue@next ', 'https://cdn.staticfile.org/vuex/3.1.0/vuex.min.js', 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js']} module. Exports = {productionSourceMap: false, chainWebpack: Config = > {/ / = = = = = = = = = = = = compressed images start = = = = = = = = = = = = config. The module. The rule (' images'). The use (' image - webpack - loader) .loader('image-webpack-loader') .options({ bypassOnDebug: True}). The end () / / = = = = = = = = = = = = compressed images end = = = = = = = = = = = = / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin (' HTML '). The tap (args If the CDN is required in the production environment or locally, To infuse the CDN the if (isProduction | | devNeedCdn) args [0]. The CDN = CDN return args}) / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = =}, configureWebpack: Config => {// Import in CDN mode, Is to ignore the related resources to build the if (isProduction | | devNeedCdn) config. The externals. = the CDN externals / / production related configure if (isProduction) {/ / code compression Config.plugins. push(new UglifyJsPlugin({uglifyOptions: {// The production environment automatically delete console compress: {warnings: Drop_debugger: true, drop_console: true, pure_funcs: ['console.log']}}, sourceMap: false, parallel: })) // gzip const productionGzipExtensions = [' HTML ', 'js', 'css'] config.plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: New RegExp (' \. (' + productionGzipExtensions. Join (' | ') + ') $'), the threshold: 10240, / / only the size is larger than the value of resources will be processed 10240 minRatio: // deleteOriginalAssets: false // delete original files})) // remove common code config.optimization = {splitChunks: { cacheGroups: { vendor: { chunks: 'all', test: /node_modules/, name: 'vendor', minChunks: 1, maxInitialRequests: 5, minSize: 0, priority: 100 }, common: { chunks: 'all', test: /[\/]src[\/]js[\/]/, name: 'common', minChunks: 2, maxInitialRequests: 5, minSize: 0, priority: 60 }, styles: { name: 'styles', test: /.(sa|sc|c)ss$/, chunks: 'all', enforce: true }, runtimeChunk: { name: 'manifest' } } } } } } }Copy the code
Using gzip compression requires nginx configuration
server{ listen 8080 server_name localhost gzip on; gzip_min_length 1k; gzip_comp_level 9; gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary on; gzip_disable "MSIE [1-6]\."; location /appShare { client_max_body_size 10m; root /home/test/webIndex/appShare; try_filtes $uri $uri/ /yourProduct/index.html; index index.htm index.html; }}Copy the code