Because of my love for Vite, I try to translate English documents for the first time, because my English level is limited. If there is any translation error or can’t get the exact meaning of the original text, please point out and correct it in time. For a better reading experience, it is highly recommended to skip to the following address.
Github.com/zhangyuang/…
Vite – design. The firm. Sh/guide/getti… Full section Address
Vite source code analysis module analysis
Vite source code analysis hot update
Vite source code analysis of the pre-optimization
Vite source code analysis component rendering
Vite ⚡ vite is an attitude web development build tool that imports your code for native development using native ES Module features. Use Rollup to package code in production.
Faster cold start times instant hot replace features true on-demand build for more details see How and Why Status is currently in beta with version 1.0 expected soon.
Quick Start For Vue users: Vite currently only supports Vue 3.x. This means that you cannot use the library npminitvite−app
Yarncreatevite −app
Yarn yarn Build Yarn Link Then go to the project created based on Vite and run yarn Link vite. Now you can restart your service (YARN Dev) to experience the latest features!
Browser Support Vite relies on native ES Module imports in a development environment. Rely on dynamic loading for code splitting during production builds
Vite assumes that your code is running on a modern browser and will use the ES2019 specification to convert your code by default. This allows the optional chain function to be used after the code is compressed. You can also manually specify the build target in the configuration options. The lowest release specification is ES2015.
Bare Module Resolving Hot Module Replacement TypeScript CSS/JSON Importing Asset URL Handling PostCSS CSS Modules CSS Pre-processors JSX Web Assembly Inline Web Workers Custom Blocks Config File HTTPS/2 Dev Server Proxy Production Build Modes and Environment Variables Vite try to reuse the vuE-CLI default configuration as much as possible. If you’ve used vue-CLI or other WebPack-based template projects before, you should be familiar with these. That means don’t expect to be any different here than there.
Bare Module considerations the native ES Imports specification does not support importing Bare modules, for example
Import {createApp} from ‘vue’ will throw errors by default. Vite will detect all.js files in the current service and override their paths like /@modules/vue. In this path, Vite will parse the execution module correctly from the dependencies you installed.
There is special treatment for the vUE dependency. If you don’t install it in your project’s local dependencies, Vite will fall back to its own dependency version. This means that if you install Vite globally, it will find Vue instances faster without having to install dependencies locally.
Hot Module Replacement Vuereact and preact templates are already integrated with Hot Replacement in create-viet-app and available out of the box. To manually control Hot Replacement, you can use the API import.meta.hot. If a module wants to receive its own replacement callback, it can use import.meta.hot.accept:
export const count = 1
// This condition determines that hot substitution-related code will be discarded in production
if (import.meta.hot) { import.meta.hot.accept((newModule) = > { console.log('updated: count is now ', newModule.count) }) } ` `A module can also receive update notifications from other modules without reloading. You can use the import. Meta. Hot. AcceptDeps: `` `js
import { foo } from './foo.js'
foo()
if (import.meta.hot) { import.meta.hot.acceptDeps('./foo.js'.(newFoo) = > { // The callback will fire newfoo.foo ()} when './foo.js' is updated.
// We can also accept an array
import.meta.hot.acceptDeps(['./foo.js'.'./bar.js'].([newFooModule, newBarModule]) = > {
// The callback function will be triggered when the modules in the array are updated})}Copy the code
Modules that receive updates from themselves or from other modules can use hot-.dispose to clean up some side effects from updates
function setupSideEffect() {}
setupSideEffect()
if (import.meta.hot) { import.meta.hot.dispose((data) = > { // cleanup side effect }) }
Copy the code
The full API can be viewed at hMR.d.ts.
Vite’s hot replace feature does not swap the source of imported modules. If a received module is repeatedly exported, it is responsible for updating those repeated exports (these exports must use lets). In addition, upstream of the receiving module will not be notified of these changes. (This part tries to write some examples to verify, but still cannot get the exact meaning of the original text.)
This neat hot replacement implementation is sufficient in many development scenarios. This allows us to skip the expensive process of generating proxy modules.
TypeScript Vite supports use in Vue single-file components
Vite only converts.ts files without type checking. It assumes that type checking is already included in your IDE or in your build commands (for example, you can run TSC –noEmit in your build script).
Vite uses esbuild to convert TypeScript to JavaScript 20-30 times faster than TSC. The update time for hot replacement will be less than 50ms in the browser.
Because esbuild only does conversions with no type information. So it does not support functions such as constant enumerations and implicit type imports. Json file you must set “isolatedModules”: true to the compilerOptions of the tsconfig.json file so that TS will warn you that these features cannot be used under this option.
CSS / JSON Importing You can directly import .css and .json files from JavaScript (including
The contents of the.json file will export an object as a default export. The.css file will not export anything unless it has a.module.css suffix. See CSS Modules. Importing it in a development environment has side effects and is injected into pages, and in production it ends up packaged separately as a style.css file. Both CSS and JSON imports support hot replace.
You can refer to static resources in the *. Vue template styles tag and.css files via either an absolute static directory path (based on your project root) or relative path (based on the current file). The latter behaves much like the file-loader you used in vue-CLI or Webpack.
All referenced resources, including those referenced using absolute paths, will eventually be copied to the packaged dist folder with the file name containing the value HAS H. Files that are not referenced will not be copied. As with vue-CLI, image resources less than 4KB will be base64 inlined.
All static resource path references, including absolute paths, are based on your current working directory structure.
The public Directory under The project provides files that do not introduce static file resource files (such as robots.txt) into The source code, or that must retain their original names (without hash values).
The files in the public directory will be copied to the final dist folder.
To reference a file in public, use an absolute path. For example, the public/icon. PNG file is referenced as /icon.png in the source code.
Public Base Path If your project is distributed as a nested folder. You can use the –base=/your/public/path/ option so that the paths of all static resources are automatically overwritten.
For dynamic path references, there are two ways to provide this
You can get parsed static file paths by importing them in JavaScript. For example, import path from ‘./foo.png’ will return the loading path as a string. If you need to concatenate the full path in the cloud, you can use the injected global variable import.meta.env.base_URL, whose value is equal to the base path of the static resource. This variable is static during the build process, so it must appear this way. Env [‘BASE_URL’] will not take effect. PostCSS Vite automatically applies PostCSS to all styles tags in *. Vue files and to all imported.css files. Just install the necessary plug-ins and add the postcss.config.js configuration file to the project root directory.
CSS Modules If you want to use CSS Modules you don’t need to configure PostCSS because it’s already integrated right out of the box. You can use them in *.vue components, and in.css files you can use the *.module. CSS suffix to import them with hash values.
CSS pre-processors because Vite expects that your code will run in modern browsers, So it suggests using native CSS variables combined with PostCSS plug-ins to implement CSSWG drafts (such as postCSS-Nesting) to make them concise and standardized. This means that if you insist on using CSS preprocessing, you need to install the preprocessor locally and use it.
yarn add -D sass
It can also be imported in a JS file
Import ‘./style. SCSS ‘Passing Options to pre-processor 1.0.0-beta.9+ if you need to change the default preprocessor configuration, You can use the cssPreprocessOptions option in the config File (view config File) for example to define a global variable for your less File // viet.config.js module.exports = { cssPreprocessOptions: { less: { modifyVars: { ‘preprocess-custom-color’: ‘green’ } } } } JSX .jsx and .tsx files are also supported. JSX transpilation is also handled via esbuild.
.jsx and.tsx files are also supported. JSX files also use esBuild for conversion.
JSX configuration with Vue3 is out of the box by default (there is currently no hot replacement for JSX syntax for Vue)
import { createApp } from ‘vue’
function App() { return {() => ‘bar’} }
function Child(_, { slots }) { return <div onClick={() => console.log(‘hello’)}>{slots.default()} }
CreateApp (App).mount(‘# App ‘) will also automatically import jSX-compatible functions. Esbuild will convert JSX to be Vue 3 compatible and can be called from the virtual node. Vue 3 will eventually provide fast custom JSX transformations that take advantage of Vue 3’s runtime.
JSX with React/Preact We prepared two scenarios: React and Preact. You can use Vite to select a solution by executing the following commands: — JSX react or — JSX preact.
If you need a custom JSX compilation rule, JSX supports customization by using the — jsX-Factory and — jsX-fragment flags in the CLI. Or use the JSX: {factory, fragment} provided by the API. For example, you can call vite — jsx-Factory =h to use h as the function call when the JSX element is created. In the configuration File (see Config File), this can be specified as follows.
// vite.config.js module.exports = { jsx: { factory: ‘h’, fragment: ‘Fragment’}} In the Preact scenario, h is automatically injected into the context, no manual import is required. However, this can lead to imports where TS expects h functions to be displayed for type inference in the case of.tsx in conjunction with Preact. In this case, you can display the specified factory configuration to disable automatic injection of h functions.
Web Assembly 1.0.0-beta.3+ Precompiled.wasm files can be imported directly. The default export returns a Promise object as an initialization function to export the WASM instance object:
import init from ‘./example.wasm’
Init ().then(exports => {exports.test()}) init also gets the imports object passed as the second argument to Webassembly.instantiate.
init({ imports: { someFunc: () => { /* … / } } }).then(() => { / … */}).wasm files smaller than the assetInlineLimit size limit will be inline as Base64 when the production environment is built. Otherwise it will be copied to the dist folder and retrieved as a static resource.
Inline Web Workers 1.0.0-beta.3+ Web worker scripts can be imported directly by adding? Worker. The default export is a custom workder constructor.
import MyWorker from ‘./worker? worker’
Const worker = new MyWorker() When built in production, workders will be base64 inlined.
Worker scripts also use import instead of importScripts(), which relies on native browser support in the development environment and only works in Chrome, but has been compiled in production.
If you don’t want to inline worker scripts, you can replace your workder script to the public folder and initialize the workder e.g. new worker (‘/worker.js’).
You can create a viet.config. js or viet.config. ts File in the current project. Vite will use it automatically. You can also explicitly specify configuration files using vite –config my-config.js.
In addition to the option to map in CLI, it also supports the alias, Transfroms, plugins option (which will be used as a subset of the configuration interface). Refer to config.ts for more comprehensive information until the documentation is complete.
Custom Blocks Custom Blocks are also supported in single-file components of Vue. Transforms for custom blocks can be specified using the vueCustomBlockTransforms option:
// vite.config.js module.exports = { vueCustomBlockTransforms: { i18n: ({code}) => {// return Transformed Code}}} HTTPS/2 Starting the service with — HTTPS will automatically generate a self-signed certificate. And the service will enable TLS and HTTP/2.
You can also customize the signing certificate using the httpsOptions option. ServerOptions for Node supports the following parameters: key, cert, CA, PFX.
Dev Server Proxy You can customize the Proxy functionality of the locally developed service using the Proxy option in the configuration file. Vite use koa – proxies] (github.com/vagusX/koa-…). It uses HTTP-proxy underneath. The key name can be a path. For more configuration, see here.
Use cases:
// vite.config.js module.exports = { proxy: { // string shorthand ‘/foo’: ‘http://localhost:4567/foo’, // with options ‘/api’: { target: ‘jsonplaceholder.typicode.com’, changeOrigin: Rewrite: path => path.replace(/^/ API /, ”)}}} Production Build Vite will be packaged when the Production environment is built. Because native ES module imports can easily lead to unacceptably long page load times in waterfall network requests.
Execute vite Build to package the application.
Internally we use Rollup to generate the final build results. The build configuration will be passed through to Rollup, and some options can be passed through through the CLI (see Build /index.ts for more information).
The Modes and Environment Variables option is used to specify the value import.meta.env.MODE and the correct Environment Variables file will be loaded.
There are two default modes: – Development for Vite and vite serve-production for Vite build
You can override the default mode with the –mode option, for example if you want to build in development mode:
Vite build –mode development When the vite command is executed, the environment variables will be loaded from the following files in the current directory
Env.[mode] # be loaded only in the mode specified by git. Git ignores only variables that begin with VITE_ are exposed in your code. For example VITE_SOME_KEY=123 will be exposed in import.meta.env.vite_some_key. But SOME_KEY=123 will not. Env files may be used by some users on the server or in build scripts. It may contain sensitive information that is not suitable to appear in the browser.
API Dev Server You can customize local development services using this API. The service accepts some plug-ins that will be injected into the Koa App instance:
const { createServer } = require(‘vite’)
Const myPlugin = ({root, // project root path, App, // Koa app instance server, // chokidar file watcher instance}) => {app.use(async (CTX, async)) // You can do some preprocessing here. These are the original requests // before Vite touches it if (ctx.path.endswith (‘.scss’)) {// Vue is already supported by default as long as the default preprocessor is installed // so the following script only applies to or JS imports like // import ‘*.scss’. console.log(‘pre processing: ‘, ctx.url) ctx.type = ‘css’ ctx.body = ‘body { border: 1px solid red }’ }
/ /... wait for vite to do built-in transforms await next() // Post processing before the content is served. Note this includes parts // compiled from `*.vue` files, where <template> and <script> are served as // `application/javascript` and <style> are served as `text/css`. // Preprocessing before the content is sent includes the following sections // compile '*.vue' files, <template> and <script> host the service as' application/javascript ', <style> Manage the service as' text/ CSS 'if (ctx.response.is('js')) {console.log('post processing: ', ctx.url) console.log(ctx.body) // can be a string or a readable stream}Copy the code
})}
CreateServer ({configureServer: [myPlugin]}).listen(3000) Build See Build /index.ts for more comprehensive options
const { build } = require(‘vite’)
; (async () => { // All options are optional. // check out src/node/build/index.ts for full options interface. const Result = await build({rollupInputOptions: {// rollupjs.org/guide/en/#b… }, rollupOutputOptions: {// rollupjs.org/guide/en/#b… }, rollupPluginVueOptions: {// github.com/vuejs/rollu… } / /… The main difference between How and Why and vue-CLI and other packaging tools is that Vite does not have a packaging process in the development environment. The import syntax of modules in the source code is sent directly by the server to the browser for execution. The browser parses them through native
Dealing with us in this way has the following advantages:
There’s no need to wait for packaging, so the cold start will be very fast and the code is compiled on demand. Only the modules actually imported by your current page will be compiled. You don’t need to wait for the entire application to be packaged to start the service. This is even more significant in apps with many pages. The performance of hot replacement will be independent of the total number of modules. This will make hot replacement very fast no matter how big your application is. The whole page refresh is slower than tool-based packaging. The import of native ES modules in the presence of a deep import chain can easily lead to network waterfalls. However, this is native development and actual compilation should not be much different. (There is no need to compile when the page reloads because the compiled results are already cached in memory)
Since compilation is done in Node, technically any code conversion can be done, and there is nothing to prevent you from bundling code that is ultimately packaged into production. In fact, Vite provides the Vite build command to precisely package your application without network waterfalls in production.
How is This Different from es-dev-server? Es-dev-server is a great project that inspired a lot of our early designs. Here are the differences between Vite and Es-Dev-server and why we don’t implement Vite as es-Dev-server middleware:
One of the main goals of Vite is to implement hot replacement, but the internal transparency of ES-Dev-Server prevents it from working well with middleware and the Vite goal does a separate job both in the development environment and at build time. You can use Vite in the development environment or at build time for the same source code without configuration. Vite is better at handling specific types of import files. Examples are.css files and static resources. For the above reasons these processes are similar to vue-cli How is This Different from Snowpack? Snowpack V2 and Vite both provide native ES module imports for local development services. Vite’s reliance on pre-optimization was also inspired by Snowpack V1. The two projects are very similar in terms of the speed of development feedback. Some notable differences are as follows:
Vite was created to handle hot replacement functionality based on native ES modules. When Vite first released a working hot replacement based on native ES modules, no other project was actively trying to put the hot replacement of native ES modules into production. Snowpack V2 also does not initially support hot replace but plans to do so in a later version. This will make the two projects more similar. Vite and Snowpack plan to work together to provide a common API specification for hot replacement of native ES modules. However, the apis of the two projects will still differ due to differences in the internal implementation of the two projects.
The solutions for both projects are packaged applications in production environments. Whereas Vite builds using Rollup, Snowpack builds using Parcel/webpack via plug-ins. Vite builds faster and smaller in many scenarios. In addition, tighter integration with the packager makes it easier to modify the Vite transformation rules and plug-ins in both development and production configurations. Vue support is a first-class feature in Vite. For example, Vite provides a much more fine-grained HMR integration with Vue, Therefore, I pay to produce the most efficient bundle. The Vite support for Vue is first-class. Vite provides more fine-grained hot replacement capabilities for Vue and tweaks to build configurations to produce the most efficient packaging results. Contribution See Contributing Guide.
Trivia vite is the french word for “fast” and is pronounced /vit/.
License MIT