Vite que

Recently, the company developed a project to useVite+vue3+TypeScriptAs a “good” front end siege city lion that still have to keep up with the pace of the company, work or still have to kubi to learn to learn especially big new things, of course, we are also starting from zero to do this thing, all saidViteveryI’ll have to see what’s going onThere it is. No more words first openIte. Js Chinese official website, after all, is especially big development, the official document is still very friendly to the people 👌.

Good guy, open to see this striking big word: the next generation of front-end development and construction tools, then I have to follow 🐮🍺, do 🐮🍺 front-end siege city lion!!

First Vite is developed from a module hot Update (HMR) server and packaged code using Rollup, preconfigured to output a set of build instructions with highly optimized static resources for production. Vite is intended to provide a more out-of-the-box configuration, while its plug-in API and JavaScript API provide a high degree of extensibility and full support for typing.

Browser support

  • In the development environment:Vite Needs in support of nativeES Modules are dynamically imported into the browser, so lower level browsers can go.
  • Production environment: The default supported browser needs to support the introduction of natives through script tagsESThe module. This can be done through the official plugin@vitejs/plugin-legacySupport for older browsers.

Get the project up and running

The use of NPM

$ npm init @vitejs/app myViteApp && cd myViteApp && npm run dev
Copy the code

The use of yarn

$ yarn create vite-app myViteApp && cd myViteApp && yarn && yarn dev
Copy the code

The directory structure

|-- public
|-- src
| |-- assets
| |-- components
| |-- App.vue
| |-- index.css
| |-- main.js
|-- .gitgnore
|-- index.html
|-- package.json  
Copy the code

Vite helps us generate directory structure is very simple, the main files and vue-cli files are the same, Vite is simple, efficient, powerful, when learning vue3 do not need to build various environments

Vite also supports a multi-page application pattern with multiple.html entry points.

Command line interface

In projects where Vite is installed, you can use the Vite executable in NPM scripts or run it directly with NPX Vite. Here are the default NPM scripts in a Vite project created by scaffolding:

{"scripts": {"dev": "vite", // start the development server "build": "vite build", // build the production environment "serve": "vite preview" // locally preview the production build product}}Copy the code

Additional command-line options can be specified, such as –port or — HTTPS. Run NPX vite –help to get a complete list of command-line options.

Vite principle analysis

Let’s first take a look at what Vite does for us and how it does it.

First take a look at the index. HTML

Let’s look at SRC /main.ts. I used ts to create it.

SRC /main.ts was introduced into index.html, main.ts was introduced into app.vue and hung in HTML.

The browser generates HTTP requests for each import through

This is the main.ts file requested after building through Vite

In short, Vite compiles static resources from Node and returns them to the browser for rendering

Why does he start so fast?

In the old days of Webpack, Rollup and other build tools, the code we wrote was generally based on the ES Module specification, with import and export between files forming a large dependency graph.

These build tools also pre-package your modules as browbrow-readable JS bundles for local development and debugging. Although there are optimizations such as lazy routing, lazy loading does not mean lazy building. Webpack still needs to pre-build your modules for asynchronous routing.

As your project gets bigger and bigger, it’s inevitable that starting up will be slower and slower, even to the minute level. HMR hot updates can take several seconds.

Vite takes advantage of the browser’s native ES Module support by writing code like this directly in an HTML file:

// index.html
<div id="app"></div>
<script type="module">
  import { createApp } from 'vue'
  import Main from './Main.vue'

  createApp(Main).mount('#app')
</script>
Copy the code

Vite starts a server locally. When the browser reads the HTML file, it sends the main. vue module request to the server only after importing it. Vite uses a series of internal dark magic, including Vue template parsing. The code is compiled and so on, parsed into a JS file that the browser can execute and returned to the browser side.

This ensures that the browser will only request and parse the module when it is actually used, maximizing the load on demand.

As explained by the diagram on the Vite website, the traditional bundle model looks like this:

The esM-based building model looks like this:

The gray areas are routes that are not used at the moment, or are not involved in the build process at all. As more routes are added to the project, the build will not slow down.

Dependent precompile

Dependency prebuild: Vite 2.0 uses ESBuild to pre-build detected dependencies before starting the development server for the user.

You may be wondering, why do we still compile at startup when we always said no-bundle? There’s a good reason for you to do this. Let’s take lodash-es as an example.

When you use import {debounce} from ‘lodash’ to import a named function, perhaps your ideal scenario is for the browser to download a file containing only that function. But it’s not that ideal. The module of debounce relies on many other functions internally, forming a dependency graph.

When the browser requests the module of Debounce, it will find that there are two imports inside the function. After that, the function will generate 600 requests inside the function, which will take about 1 second.

This, of course, was not acceptable, so You came up with a compromise, taking advantage of Esbuild’s extremely fast build speed, allowing you to pre-package all the internal modules used by debounce into a traditional JS bundle at boot time without even knowing it.

Esbuild is written in Go and is 10-100 times faster than packager prebuilt dependencies written in JavaScript.

Before httpServer.Listen starts the development server, this function is hijacked and rewritten into a pre-built step that relies on Vite to start the server-related code.

// server/index.ts const listen = httpServer.listen.bind(httpServer) httpServer.listen = (async (port: number, ... args: Any []) => {try {await container.buildStart({}) httpServer.emit('error', e) return } return listen(port, ... args) }) as anyCopy the code

The code for runOptimize is in The Github Optimizer.

First, it scans for dependencies based on the entry of this run:

let deps: Record<string, string>, missing: Record<string, string> if (! newDeps) { ; ({ deps, missing } = await scanImports(config)) }

{
  "lodash-es": "node_modules/lodash-es"
}
Copy the code

They are then pre-packaged into single-file bundles using Esbuild based on the analyzed dependencies.

const esbuildService = await ensureService() await esbuildService.build({ entryPoints: Object.keys(flatIdDeps), bundle: true, format: 'esm', external: config.optimizeDeps? .exclude, logLevel: 'error', splitting: true, sourcemap: true, outdir: cacheDir, treeShaking: 'ignore-annotations', metafile: esbuildMetaPath, define, plugins: [esbuildDepPlugin(flatIdDeps, flatIdToExports, config)] })Copy the code

The pre-built module is returned when the browser requests the related module. In this way, when the browser requests the Debounce module in Lodash-es, the interface request is guaranteed to occur only once.

You can think of this as the same build that Webpack does, only dozens of times faster.

During the pre-build step, the CommonJS Module is also analyzed for the convenience of later processing into an ES Module that can be executed by the browser.

To compare

Other modern build tools that emerged at the same time as Vite include:

  • Snowpack – The faster frontend build tool
  • Preactjs/WMR: 👩🚀 The tiny all-in-one development Tool for modern Web Apps.
  • Web Dev Server: Modern Web

Snowpack

Snowpack is similar to Vite in that it is based on the ESM to load development environment modules, but it is built at the user’s choice, and the overall packaging experience is somewhat fragmented.

Vite integrates directly with Rollup, giving users a complete, out-of-the-box solution, and thanks to these integrations, it’s easy to extend more advanced features.

WMR

WMR is designed for Preact, so if you’re using Preact, you can use this tool first.

@web/dev-server

The tool does not provide out-of-the-box framework support and requires manual Rollup build configuration, but many of the tools included in the project will benefit Vite users as well.

For a more detailed comparison, refer to the Vite documentation – Comparison

conclusion

Vite is a magic build tool that is proposed to replace Webpack. It is not surprising that technology changes rapidly. It is necessary for us to master cutting-edge technology to optimize project solutions. But Webpack has been a great build tool in the last generation, and it’s only because of new features that there are solutions to its problems.

For now, I personally think that some light weight projects (which don’t require a particularly weird dependency build) can start experimenting with Vite, such as light weight enterprise projects (such as the one being developed by The Ape company) and demo projects in various frameworks and libraries.

In the end, welcome each big guy to criticize correct, positive admit wrong (die not repentant 🤪).