Webpack5 learning -- code compression

coderwxf 2021-09-15 06:28:32
webpack5 webpack learning code compression


Terser

Terser It's a JavaScript The explanation of (Parser)、Mangler( Meat grinder defacing )/Compressor( compressor Remove unused code , Compress multiple lines of code into one line ) The toolset of

Terser Can help us compress 、 Vilify our code , Let's have bundle To become smaller

Terser It's a stand-alone tool , It can be installed separately

In the early days we would use uglify-js To compress 、 Vilify our JavaScript Code , But it is no longer maintained , And does not support ES6+ Of grammar ;

Terser It's from uglify-es fork Over here , And keep most of it API And adaptation uglify-es and uglify-js@3 etc.

# install 
npm i terser
 # Use 
npx terser ./src/index.js -o index.min.js
# Equivalent to 
npx terser ./src/index.js -o index.min.js -c defaults
 # Multiple options are separated by commas 
# If only the option name , If there is no configuration value, the default value is used 
npx terser ./src/index.js -o index.min.js -c arrows,arguments=true
 # Compress using the default form , By default, only the parameters of the function are compressed 
npx terser ./src/index.js -o index.min.js -m
 # All the code is compressed 
npx terser ./src/index.js -o index.min.js -m toplevel=true
 Copy code 

however , In actual development , We use... From zero Terser Configure our code accordingly , It's very cumbersome , So webpack Using built-in plug-ins TerserWebpackPlugin, This plug-in has internal pairs terser A series of general default configurations are made .

TerserWebpackPlugin So we don't have to go through it manually terser To handle our code , But directly through webpack To deal with it

because webpack The internal default will use TerserWebpackPlugin, So we can just introduce it directly , because TerserWebpackPlugin It's been done webpack The dependencies are installed

To configure

stay webpack There is one of them. minimizer attribute , stay production In mode , The default is to use TerserPlugin To handle our code

If we are not satisfied with the default configuration , You can also create your own TerserPlugin Example , And override the relevant configuration

  1. First , We need to open it minimize, Let it compress our code ( Default production Mode has been turned on , If it's in development When used in mode , It needs to be opened manually )

  2. secondly , We can do it in minimizer Create a TerserPlugin Options , And configure it accordingly

optimization: {
minimizer: [
new TerserPlugin({
// Will not comments To withdraw 
extractComments: false,
// Whether to use multithreading for compilation --- The default value is true
// It can be set to number, That is, manually specify how many processes to set for packaging 
// Can also be set to true, here parallel The value is cpus.length - 1
parallel: true,
terserOptions: {
// Right here. terser Do manual configuration 
// The configuration here overrides the default terser Configuration in 
}
})
]
}
 Copy code 

CSS Compress

CSS Compression is usually to remove useless spaces, etc , Because it's hard to modify selectors 、 Name of property 、 It's worth waiting for ;

CSS We can use another plug-in :css-minimizer-webpack-plugin

# install 
npm install css-minimizer-webpack-plugin -D
 Copy code 

To configure

plugins: [
new CssMinimizerWebpackPlugin()
]
 Copy code 

Scope Hoisting

Scope Hoisting from webpack3 A new feature that began to be added

The function is to promote the scope , And let webpack The packaged code is smaller 、 Run faster

By default webpack Packaging will have many function scopes , Including some ( Like the outermost )IIFE

  • Whether it's running from the beginning of the code , Or load a module , All need to execute a series of functions ;
  • Scope Hoisting Functions that can be merged into a module , Merge all into one module to run , So as to save the performance consumption of unnecessary function calls
  • webpack Running Scope Hoisting When , In fact, it depends on ES Module Static analysis of ,
  • So in webpack It is recommended that all modules be introduced and used ES Module Use in a way

Use Scope Hoisting Very simple ,webpack Corresponding modules have been built in :

  • stay production In mode , By default, this module will be enabled
  • stay development In mode , We need to open the module ourselves ;
plugins: [
new webpack.optimize.ModuleConcatenationPlugin()
]
 Copy code 
版权声明
本文为[coderwxf]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909122358648p.html

  1. Mid Autumn Festival special! Use the simplest animation animation to make the most local and trendy holiday blessing greeting card. This romantic male and female tears of Xiao Chen.
  2. Wang Ou went back to the hotel with the man at night. It was suspected that his relationship was open. The netizen replied mercilessly: is the man single
  3. 借助HTML ping属性实现数据上报
  4. APNG在线制作、兼容、播放和暂停
  5. Apng production, compatibilité, lecture et pause en ligne
  6. Mise en œuvre de l'escalade des données avec l'attribut de Ping HTML
  7. Comment envoyer 100 000 requêtes http le plus rapidement possible
  8. JQuery Basics
  9. Front and back end data interaction (V) -- what is Axios?
  10. Serverless is a model architecture invented driven by economic benefits- Grady
  11. Les questions d'entrevue pour les ingénieurs Java d'Internet, les intervieweurs rencontrés sont tous de niveau architecte,
  12. Cinq ans d'entrevue d'expérience en développement Java, découvrez les questions que vous devez poser lors de l'entrevue d'embauche du printemps Java de cette année.
  13. La dernière collection de questions d'entrevue Java haute fréquence organisée cette année, 2021 Java Universal Popular Framework
  14. Intel selected Weilai es8 to promote driverless taxis in Europe
  15. JavaScript operator (1), Web Development Engineer
  16. Trier les questions d'entrevue Javascript, trier les points de connaissance des itinéraires d'apprentissage
  17. Song Mengjun's "sleepless night" triggered an upsurge of dance storm after 00
  18. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  19. Encapsulated PHP sends HTTP requests with curl. Get and post are very easy to use
  20. Front and back end data interaction (V) -- what is Axios?
  21. Flutter: résoudre le futur blocage en utilisant Isolate
  22. Résumé des opérations courantes pour les données de structure de l'arbre frontal
  23. Ant Design Transfer Twin Tree Shuttle box "make Wheels"
  24. De la carte de pensée à la base et à l'approfondissement, prenez note de l'expérience d'entrevue d'un octet sautant le poste de recherche et développement Java.
  25. Apprenez les composants d'implémentation de vue et Publiez - les à NPM
  26. [Questions d'entrevue à haute fréquence] À vous de choisir
  27. Une faible connaissance de beginpath () provoque une superposition de style lors de la peinture d'un dessin en toile
  28. React Hooks, laisse - moi t'emmener étudier.
  29. Comment la copie profonde résout - elle les références circulaires?
  30. JavaScript Advanced Programming (3rd Edition) Reading note 6
  31. Analyse de l'URL
  32. Discussion préliminaire sur xss
  33. Solution: développement de la page Web Wechat, obtenir la fosse Piétinée par le flux d'entrée de la caméra via navigator.mediadevice.getusermedia ()
  34. Des milliers de questions d'entrevue sélectionnées n'ont pas encore ét é effacées.
  35. Les questions d'entrevue de niveau intermédiaire et avancé d'Android au fil des ans sont entièrement incluses, et l'algorithme est distribué microservice
  36. J'ai résumé toutes les questions d'entrevue.
  37. Compréhension de la réactivité des données de vue
  38. Note de service CSS (vi): Flex, page mobile et mise en page réactive
  39. Non-ASCII character ‘\xe5‘ in file kf1.py on line 4, but no encoding declared; see http://python.or
  40. 手把手教你搭建微信小程序服务器(HTTPS)
  41. JavaScript Review sketch - 1
  42. Analyse du bootstrap webpack
  43. sqli-labs-less-18 http头user agent+报错注入
  44. Génération de code nest pour l'outil CLI de nestjs
  45. JS | This
  46. Augmentation des variables
  47. The sinking gs8 raises its flag again. GAC motor's sales are falling endlessly. Is it the car or the people?
  48. Ren Hao's lunch at work today is president Hao wearing a sleeveless coat! Clean and handsome!
  49. Summary of basic knowledge points of JavaScript language (mind map)
  50. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  51. Sqli Labs - less - 18 http header user agent + Error Reporting Injection
  52. Vous apprendrez à construire un serveur d'applet Wechat (https) à la main
  53. Non - ASCII character 'xe5' in file kf1.py on Line 4, but no Encoding declared;Voirhttp://python.or
  54. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  55. En tant que programmeur, quelle est la plus grande tristesse que vous ressentez? L'entrevue d'emploi Java de 2021 dans une grande usine vous demandera:
  56. En tant que programmeur, je n'oublie pas le dernier résumé de mon expérience d'entrevue de stage en Java.
  57. Experts suggested that performers work with certificates, which triggered a collective heated debate. It is meaningless to be accused of repeating the mistakes
  58. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  59. The appearance value of 200000 "Odyssey" is less than 100000, and has become the "sales champion" of household MPV
  60. Les programmeurs Java qui sont entrés dans l'entreprise pendant trois mois ont dû faire face à une correction d'échelle, et les octets ont sauté dans le traitement des questions d'entrevue de JD 360 Netease.