For large projects, there are dozens or hundreds of dynamic routing components. Webpack packs everything into memory at compile time, but Vite is just a routing component for dynamic requests at run time, which is a real speed boost!

Vite leverages modern browsers’ natural support for import modularity to dynamically request dependent files at run time. That is, if hash is ‘#a’, ‘a.js’ is requested, not ‘b.js’. If hash is ‘#b’, ‘b.js’ is requested, not ‘a.js’.

Without further ado, let’s get right to the code

1. index.html

<! Type ="module" -->
<script src="./main.js" type="module"></script>
Copy the code

2. main.js

// Assume the current route is 'a'
let hash = window.location.hash || '#a'

if (hash === '#a') {
  // If the route is 'a', the 'a.js' file is requested dynamically at run time
  import('./a').then(a= > {
    a.default()
  })
} else if (hash === '#b') {
  // If the route is 'b', the 'b.js' file is requested dynamically at run time
  import('./b').then(b= > {
    b.default()
  })
}
Copy the code

3. a.js

export default function a() {
  document.write('a...... ')}Copy the code

4. b.js

export default function b() {
  document.write('b...... ')}Copy the code

In order to test the vite Server, I have written the vscode plugin. Search for vite in the vscode plugin market. Note that the author of the download is Rui Ge, click the right button and execute ‘Open with vite Server’ directly.

The measured

  1. If hash is ‘#a’, request ‘a.js’, not ‘b.js’
  2. If hash is ‘#b’, request ‘b.js’, not ‘a.js’

Finally, you are welcome to download the Vite plugin and enjoy the fast experience of Vite right away