Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money
Vite from entry to master | advanced application
This article summarizes the advanced applications in Vite, including HMR hot update, Glob-import batch import function, precompilation optimization to improve Vite performance,Vite integration in non-Node services, the use of SSR in Vite, static site export,Vite configuration items summary and other applications
HRM hot Update in Vite
Create HRM through the Vanilla project
Create a project
$NPM init @vitejs/app ➤ Project Name:... Vite-project ✔ Vanilla ➤ Select a framework from a variantCopy the code
Implement single file HMR hot update
import './style.css'
export function render () {
document.querySelector('#app').innerHTML = ` Hello Vite!
Documentation `
}
render()
/ / integration HMR
Hot does not exist in vite build
// Normal paradigm: Set up HRM hot update in the development environment
if (import.meta.hot) {
// Receive hot updates
// The current file for newModule
// After Vite receives the file update, it executes this method to rerender
import.meta.hot.accept((newModule) = >{ newModule.render(); })}Copy the code
Attached source: github.com/xujiantong/…
Glob-import batch import function in Vite
Glob-import: A set of files can be imported using regular expressions
Glob-import is implemented through the viet-vue3 project
Create a project
$NPM init @vitejs/app ➤ Project Name:... Vite-project ➤ ➤ Select a framework from vue ➤ ➤ a variantcd vite-project
$ yarn
$ yarn dev
Copy the code
Ready to file
Create a glob folder in the SRC directory and create the files
cd src
mkdir glob
touch a.js a.json b.js b.json test-1.js
# File contents see source code
# https://github.com/xujiantong/vite-senior-apply/tree/feat/glob
Copy the code
Import all files under glob with one click in mian.js
Import all files
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const globModules = import.meta.glob("./glob/*")
console.log(globModules)
createApp(App).mount('#app')
Copy the code
Use the data in the file
import { createApp } from 'vue'
import App from './App.vue'
const globModules = import.meta.glob("./glob/*")
console.log(globModules)
// Check the Key Value
Object.entries(globModules).forEach(([k,v]) = > {
console.log(k+ ":" + v)
v().then(m= > console.log(k + ":" ,m.default))
})
createApp(App).mount('#app')
Copy the code
Application scenarios
multilingual
Just introduce JS
const globModules = import.meta.glob("./glob/*.js")
Copy the code
I just want to introduce json files
const globModules = import.meta.glob("./glob/*.json")
Copy the code
Only files with the specified re are imported
const globModules = import.meta.glob("./glob/*-[0-9].json")
Copy the code
Glob-import is a feature provided by Vite
Source: github.com/xujiantong/…
Precompilation in Vite
For third-party libraries installed in node_modules, Vite compiles the packages we rely on in the Cache before the first startup, and then the program goes back to the Cache to fetch them.
/node_modules/.vite
-
CommonJS to ESM: Non-ESM files will be compiled to ESM
- During development, Vite relies on the browser’s native ESM loading method to load files
-
The configurable vite.config.js specifies what is required to be precompiled
// vite.config.js
export default defineConfig({
plugins: [vue()],
optimizeDeps: {
exclude: ["react"].include: ["vue"],}})Copy the code
- Bundle files together
Non-nodejs services integrate with Vite
Non-nodejs services: Java Go Python…
-
The template engine uses Vite
-
Lead-in path problem
Template engine adds labelsDev
<script type="module" src="http://localhost:3000/@vite/client"> </script>
<script type="module" src="http://localhost:3000/src/main.js"></script>
Copy the code
Resolving the path problemdev
Set static directory path mapping on the server
How to deal with packaging production?
// vite.config.js
build: {manifest: true
}
Copy the code
Server parsed the manifest. Json
Output index, vendor, and CSS to the template
Receive variables on the template
How do I integrate Vite with Nodejs
Basic version
yarn add express
// server.js
const express = require("express")
const app = express()
const { createServer: createViteServer} = require("vite")
createViteServer({server: {
middlewareMode: 'html'.// html: vite dev server, ssr:
}}).then((vite) = > {
app.use(vite.middlewares)
app.listen(4000)})Copy the code
Server rendering SSR
The development environmentDev
const express = require("express")
const fs = require("fs")
const app = express()
const { createServer: createViteServer} = require("vite")
createViteServer({server: {
middlewareMode: 'ssr'.// html: vite dev server, ssr:
}}).then((vite) = > {
app.use(vite.middlewares)
app.get("*".async (req,res)=> {
let template = fs.readFileSync('index.html'.'utf-8')
template = await vite.transformIndexHtml(req.url, template)
const {render} = await vite.ssrLoadModule('/src/server-entry.jsx')
const html = await render(req.url)
const responseHtml = template.replace("<! --APP_HTML-->", html)
res.set("content-type"."text/html").send(responseHtml)
})
app.listen(4000)})Copy the code
Vite Config
// vim vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// Introduce JSX dependencies
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
root: "".// Where index. HTML exists
base: ". /".// Specifies the prefix of the requested resource path (URL), default./
mode: "development".--mode specifies env and defaults to "development" and "production".
define: "".// ≈ rollup definePlugin, which defines how to replace global constants
plugins: [ // Use plugins
vue(),
vueJsx(),/ / to use vue - JSX].publicDir:"".// Static resource directory
cacheDir: "".// Node_modules /.vite
resolve: {
alias: {},// alias, path mapping: "@styles": "/ SRC /styles"
dedupe: [].// If there is a copy of the same dependency, such as vue2, vue3 installed, use this property to specify which dependency to use
conditions: [].// Resolve additional permissible conditions for exporting scenarios in the package
mainFields: [].// package.json, the list of fields to try when parsing the entry point of the package. Note: This is lower priority than exporting from the exports field resolution scenario: if an entry point resolves successfully from exports, resolve. MainFields will be ignored.
extensions: [].// List of extension names you want to omit when importing. It is not recommended to ignore the extension of a custom import type (for example:.vue) because it affects the IDE and type support.
},
css: {
modules: [].// Sets the behavior of the CSS modules
postcss: "".// Inline PostCSS configuration (in the same format as postcss.config.js)
preprocessorOptions: {// Specifies the options passed to the CSS preprocessor
scss: {
additionalData: `$injectedColor: orange; `}}},json: {
namedExports:true.// Whether import by name from.json files is supported.
// You are advised to enable ~ if the json file is too large
stringify: false.Parse ("...") export default json.parse ("... ), which will perform better than translating to object literals, especially if JSON files are large. If this option is enabled, import by name is disabled.
},
esbuild: {}, // ESbuild conversion option
assetsInclude: {
assetsInclude: ['**/*.txt']},// Specify additional Picomatch patterns to be handled as static resources, for example I want to import a TXT file
logLevel: 'info'.// Prints the log level
clearScreen: true.envDir: "".//. Env Directory for storing files
build: {
target: 'modules'.// Set the browser compatibility target for the final build
polyfillModulePreload: true.// Polyfill used to determine whether to automatically inject module preload.
outDir: "dist".// Specify the output path
assetsDir: "assets".// Static resource storage path
assetsInlineLimit: "4096".// 4KB, import or reference resources less than this threshold will be base64 encoded inline to avoid additional HTTP requests. Setting this to 0 disables this item completely.
cssCodeSplit: true.// CSS file split
sourcemap: 'hidden'.// Whether to generate the source map file after the build.
rollupOptions: {},commonjsOptions: {},dynamicImportVarsOptions: {},lib: {},manifest: false.// When set to true, the manifest.json file will be generated after the build, containing the unhashed resource file name and the hash version mapping. Some server frames can be rendered with the correct resource import links.
ssrManifest: false.minify: 'esbuild'.terserOptions: {},
write: true.// Set to false to disable writing the built files to disk. This is often used to programmatically call build() that requires further processing of the built file before it can be written to disk.
emptyOutDir: true.// Whether to empty dist first when building
brotliSize: true.// Compress the report after the build
chunkSizeWarningLimit: 500.// Compression over 500K alert
watch: null.// Set to {} to enable rollup's listener. This is often used when dealing with build-only plug-ins and in integrated development processes.
// Depend on optimization items
optimizeDeps: {
entries: "".include: [].exclude: [].keepNames: false.// true Renames symbols to avoid collisions}}})Copy the code