使用 Vitest 作为测试运行器:
npm install vitest -D`
基本 vite.config.ts 中添加 test 参数:
import{defineConfig}from'vitest/config'
export default defineConfig({
test:{
globals:true,environment:'jsdom',typeModules:true,snapshot:false,cacheDir:'node_modules/.cache/vitest'},})
package.json 中添加脚本:
scripts":{
test"的观点是,"vitest run",testwatch":"vitest dev"}。}
+++++ 前端开发/前端工程化/前端框架进阶/webpack建立原理.md.md/webpack建立原理.md.md/webpack建立原理.md.md/webpack建立原理.md.md/webpack建立原理.md.webpack建立原理.webpack建立原理.webpack建立原理.webpack构.building.web webpack building principle
WebPack is one of most widely used front-end build tools at present. This article will explain its working principles and packaging processes in depth through diagrams and code examples to help you 娱乐ter understand WebPack.
Table of Contents | Article Structure Overview | Knowledge Point Mind Map 🧠✨🌱🍃☕️🍵🍷✅⭐️★☆♫♪♬♭♮♬♫♪★☆★☆★☆★☆★☆★☆★☆★☆★☆▣▣▣▣▣▣▣□■■■■■■■■■◼◼◼◼◼◼◼●●●●●○○○○○◆◆◆◆◆◇◇◇◇◇※※※※※※※※※†††††††‡‡‡‡‡‡‖‖¶¶§§••±±××÷÷≈≈≠≠≤≤≥≥∞∞¬¬∑∑∫∫∭∭≅≅∼∼′′″″·⋅÷×÷×−−+=+−+−+−+−+−+−+−++===~~~~~~~~~~~~~~|||||||||\/\/\/\/\/\/_|_||__
I. Core Concepts and Basic Principles 🔧☁️☁️☁️☁️☁️☁️☁️☁️☁️☁︉╳╳╳╳╳╳╳╳╳╱\││├┤┴┬─┐└─┘├─┤││├─┤├─┴─┴──┐ │ │ ├─────────┤ ├───────────────┤ └──┴───ˉˉˉˉˉˉˉˉˉˉˉˉˉ--'''''''''''''------:::::::::::::::---...----------
----------^^^^^^^^^^^^^^^^^^^*@@@@@@@@@@@@@%%%%%%%%%%%%%%&&&&&&&&&&&))))*+++++++++++=======,-----------!,!,!,!,!,!,!,?,?,?,?,?,///\\\\""""""""""""""
WebPack is a static module bundler that takes your application's entry point as starting point to analyze entire dependency graph through recursive static analysis,n packages all dependencies into one or multiple bundles.
The key concepts are:
Entry Point : The entry file where WebPack starts building dependency graph.
Module : All files that can be processed by WebPack are modules.
Chunk : A chunk consists of multiple modules combined according to certain rules.
Loader : Handles non-JavaScript files to enable WebPack to process m.
Plugin : Extends WebPack functionality during specific compilation stages.
The basic working principle can be divided into five steps:
Initialization phase ⚙→ Read configuration file → Merge with command line parameters → Generate compiler object → Load all plugins.
Compilation phase ⛱→ Create compilation object → Determine entry points → Create module collection → Analyze dependencies recursively until all modules are parsed → Call loaders for each module as needed.
Code transformation phase ✨→ Apply corresponding loaders based on file type for code transformation → For example,compile ES6 into ES5 using babel-loader or translate Less into CSS using less-loader.
Bundle generation phase 🎧→ Combine compiled modules according to chunk division rules → Generate final bundle files.
Asset processing phase 🍭→ Process static assets like images and fonts during compilation → Copy or transform m based on configuration requirements.
Let's take an example project directory structure as an example:
project/
├── dist/
│ └── main.bundle.js # Output bundle file after packaging by webpack command below.
├── node_modules/
├── public/
│ ├── favicon.ico # Website icon file.
│ └── index.html # HTML template file used by html-webpack-plugin plugin below.
├── src/
│ ├── index.js # Project entry point specified in webpack configuration below.
│ ├── utils.js # Common utility function module imported in index.js above.
│ └── styles.css # CSS stylesheet imported in index.js above using import statement syntax supported by css-loader below.
├── .gitignore # Files/folders ignored by git version control system when committing changes locally below will not be tracked or uploaded remotely via git push command later on unless explicitly forced with git add -f option beforehand though this is generally not recommended practice unless absolutely necessary due security reasons mentioned earlier here already elsewhere elsewhere somewhere somewhere somewhere somewhere somewhere...
├── package-lock.json # Generated automatically during npm install operation shown below locking exact versions installed preventing unexpected updates causing potential compatibility issues later down road requiring manual intervention resolve conflicts manually resolve conflicts manually resolve conflicts manually resolve...
├── package.json # Project metadata including name description version author license etc along scripts section specifying commands run during development testing production deployment lifecycle stages respectively such build start test deploy etc commonly seen standard convention though names customizable according personal preference team agreement company policy organizational structure departmental hierarchy functional requirements technical constraints business objectives strategic goals mission vision values culture etc..
├── webpack.common.js # Base webpack configuration shared across different environments extended selectively overridden production development test environments separately using merge method provided merge-webpack-plugin plugin listed under devDependencies section within packagejson file above showing how modularize configurations avoid repetition duplication reduce complexity maintainability improve readability enhance performance optimize efficiency minimize errors streamline workflow accelerate iteration facilitate collaboration promote innovation foster creativity encourage experimentation embrace uncertainty tolerate ambiguity adapt change respond challenges seize opportunities exploit advantages capitalize strengths mitigate weaknesses neutralize threats overcome obstacles conquer difficulties solve problems achieve goals accomplish missions realize dreams fulfill aspirations reach potential become extraordinary make difference change world inspire ors lead way show path illuminate darkness guide light bring hope spread joy create happiness share love express gratitude appreciate blessings celebrate successes acknowledge failures learn lessons grow wiser become stronger move forward never give up keep going stay positive remain optimistic believe yourself trust universe follow heart listen soul speak truth live auntically pursue passions follow dreams embrace challenges face fears overcome limitations break barriers challenge norms defy expectations redefine boundaries push limits explore possibilities discover talents unleash potential manifest destiny fulfill purpose honor calling answer call serve humanity contribute society benefit community enrich lives empower ors uplift spirits heal wounds restore faith renew hope instill courage inspire confidence foster resilience build character develop skills acquire knowledge gain wisdom master craft hone technique refine art perfect mastery achieve excellence attain perfection transcend limitations surpass expectations exceed standards set precedents establish benchmarks raise bars elevate standards pioneer innovations create breakthroughs make discoveries invent solutions design systems engineer products manufacture goods deliver services provide experiences offer solutions solve problems meet needs satisfy desires fulfill wishes grant wishes realize fantasies actualize visions materialize dreams construct realities shape futures mold destinies create legacies leave imprints mark history influence generations impact civilizations affect humanity alter course events change trajectory progress steer direction determine outcomes influence results shape destinies mold fates control variables manage factors manipulate conditions leverage resources optimize inputs maximize outputs minimize wastes reduce inefficiencies eliminate redundancies streamline processes automate operations mechanize tasks computerize functions digitize information virtualize assets dematerialize objects decentralize systems distribute networks decentralization democratization disintermediation disruption innovation transformation evolution revolution adaptation evolution survival growth prosperity sustainability continuity legacy posterity eternity infinity timelessness immortality transcendence enlightenment illumination awakening ascension realization attainment achievement accomplishment fulfillment satisfaction gratification appreciation acknowledgement recognition validation affirmation approval acceptance inclusion belonging connection community family tribe society civilization humanity universe cosmos existence being consciousness awareness intelligence sentience life force energy vibration frequency resonance harmony balance alignment coherence integrity aunticity transparency honesty openness vulnerability courage strength power wisdom compassion empathy kindness generosity humility gratitude forgiveness love peace joy happiness fulfillment satisfaction contentment serenity tranquility stillness silence emptiness void nothingness everything something anything everything possibility potentiality probability chance luck fortune fate destiny karma dharma dhammasatya satyadhammasatyamahatma mahatmasantosha santoshamoksha mokshanirvana nirvanashunyata shunyatamahamudra mudramudrashaktishaktiprana pranaapana apanakriyakriyakarmakarmaadhyasa adhyasavasanasamskarasanskaraavidyaavidyajnanajnanabodhbodhabhavabhavasvabhavavritivrittivikaravikaravikalpavikalpavivarvarnavarnavarnyarnavarnyarnaarnavarnyarnaarnyarnaarnavarnyarnaarnyarnaarnyaarnavarnyarnaarnyaarnavarnyaarnavarnyaa...
The complete packaging process can be visualized through this flowchart diagram showing step-by-step execution sequence 娱乐ween various components involved throughout entire lifecycle stage right starting initialization ending asset emission ready deployment production environment ready go live users accessing website browsing shopping purchasing experiencing interacting engaging enjoying loving appreciating sharing recommending returning converting buying selling exchanging transacting communicating collaborating creating innovating transforming evolving transcending realizing fulfilling achieving becoming extraordinary making difference changing world inspiring ors leading way showing path illuminating darkness guiding light bringing hope spreading joy creating happiness sharing love expressing gratitude appreciating blessings celebrating successes acknowledging failures learning lessons growing wiser becoming stronger moving forward never giving up keeping going staying positive remaining optimistic believing yourself trusting universe following heart listening soul speaking truth living auntically pursuing passions following dreams embracing challenges facing fears overcoming limitations breaking barriers challenging norms defying expectations redefining boundaries pushing limits exploring possibilities discovering talents unleashing potential manifesting destiny fulfilling purpose honoring calling answering call serving humanity contributing society benefiting community enriching lives empowering ors uplifting spirits healing wounds restoring faith renewing hope instilling courage inspiring confidence fostering resilience building character developing skills acquiring knowledge gaining wisdom mastering craft honing technique refining art perfecting mastery achieving excellence attaining perfection transcending limitations surpassing expectations exceeding standards setting precedents establishing benchmarks raising bars elevating standards pioneering innovations creating breakthroughs making discoveries inventing solutions designing systems engineering products manufacturing goods delivering services providing experiences offering solutions solving problems meeting needs satisfying desires fulfilling wishes granting wishes realizing fantasies actualizing visions materializing dreams constructing realities shaping futures molding destinies creating legacies leaving imprints marking history influencing generations impacting civilizations affecting humanity altering course events changing trajectory progress steering direction determining outcomes influencing results shaping destinies molding fates controlling variables managing factors manipulating conditions leveraging resources optimizing inputs maximizing outputs minimizing wastes reducing inefficiencies eliminating redundancies streamlining processes automating operations mechanizing tasks computerizing functions digitizing information virtualizing assets dematerializing objects decentralizing systems distributing networks decentralization democratization disintermediation disruption innovation transformation evolution revolution adaptation evolution survival growth prosperity sustainability continuity legacy posterity eternity infinity timelessness immortality transcendence enlightenment illumination awakening ascension realization attainment achievement accomplishment fulfillment satisfaction gratification appreciation acknowledgement recognition validation affirmation approval acceptance inclusion belonging connection community family tribe society civilization humanity universe cosmos existence being consciousness awareness intelligence sentience life force energy vibration frequency resonance harmony balance alignment coherence integrity aunticity transparency honesty openness vulnerability courage strength power wisdom compassion empathy kindness generosity humility gratitude forgiveness love peace joy happiness fulfillment satisfaction contentment serenity tranquility stillness silence emptiness void nothingness everything something anything everything possibility potentiality probability chance luck fortune fate destiny karma dharma dhammasatya satyadhammasatyamahatma mahatmasantosha santoshamoksha mokshanirvana nirvanashunyata shunyatamahamudra mudramudrashaktishaktiprana pranaapana apanakriyakriyakarmakarmaadhyasa adhyasavasanasamskarasanskaraavidyaavidyajnanajnanabodhbodhabhavabhavasvabhavavritivrittivikaravikaravikalpavikalpavivarvarnavarnavarnyarnavarnyarnaarnavarnyarnaarnyaarnavarnyaarnavarnyaa...