Vite(四)后端集成、比较Snowpack、从 v1 迁移、Awesome Vite.js
文章目录
- 网址:https://vitejs.cn/guide/why.html
1. 后端集成
如果你想使用传统的后端(如 Rails, Laravel)来服务 HTML,但使用 Vite 来服务其他资源,可以查看在 Awesome Vite 上的已有的后端集成列表。
或者你可以按照如下步骤手动配置:
在你的 Vite 配置中配置入口文件和启用创建
manifest:// vite.config.js export default { build: { // 在 outDir 中生成 manifest.json manifest: true, rollupOptions: { // 覆盖默认的 .html 入口 input: '/path/to/main.js' } } }别忘记在你的入口添加 dynamic import polyfill,因为它不会自动注入了:
// 添加到你应用入口文件的开头 import 'vite/dynamic-import-polyfill'在开发环境中,在服务器的 HTML 模板中注入以下内容(用正在运行的本地 URL 替换
http://localhost:3000):<!-- 如果是在开发环境中 --> <script type="module" src="http://localhost:3000/@vite/client"></script> <script type="module" src="http://localhost:3000/main.js"></script>还要确保服务器配置为提供 Vite 工作目录中的静态资源,否则图片等资源将无法正确加载。
如果你正使用
@vitejs/plugin-react-refresh配合 React,你还需要在上述脚本前添加下面这个,因为插件不能修改你正在服务的 HTML:<script type="module"> import RefreshRuntime from "http://localhost:3000/@react-refresh" RefreshRuntime.injectIntoGlobalHook(window) window.$RefreshReg$ = () => {} window.$RefreshSig$ = () => (type) => type window.__vite_plugin_react_preamble_installed__ = true </script>在生产环境中:在运行
vite build之后,一个manifest.json文件将与静态资源文件一同生成。一个示例清单文件会像下面这样:{ "main.js": { "file": "assets/main.4889e940.js", "src": "main.js", "isEntry": true, "dynamicImports": ["views/foo.js"], "css": ["assets/main.b82dbe22.css"], "assets": ["assets/asset.0ab0f9cd.png"] }, "views/foo.js": { "file": "assets/foo.869aea0d.js", "src": "views/foo.js", "isDynamicEntry": true, "imports": ["_shared.83069a53.js"] }, "_shared.83069a53.js": { "file": "assets/shared.83069a53.js" } }- 清单是一个
Record<name, chunk>结构的对象。 - 对于 入口 或动态入口 chunk,键是相对于项目根目录的资源路径。
- 对于非入口 chunk,键是生成文件的名称并加上前缀
_。 - Chunk 将信息包含在其静态和动态导入上(两者都是映射到清单中相应 chunk 的键),以及任何与之相关的 CSS 和资源文件。
你可以使用这个文件来渲染链接或者用散列文件名预加载指令(注意:这里的语法只是为了解释,实际使用时请你的服务器模板语言代替):
<!-- 如果是在生产环境中 --> <link rel="stylesheet" href="/assets/{{ manifest['style.css'].file }}" /> <script type="module" src="/assets/{{ manifest['index.js].file }}"></script>- 清单是一个
2. 比较
Snowpack
Snowpack 也是一个与 Vite 十分类似的非构建式原生 ESM 开发服务器。除了不同的实现细节外,这两个项目在技术上比传统工具有很多共同优势。Vite 的依赖预绑定也受到了 Snowpack v1(现在是 esinstall)的启发。这两个项目之间的一些主要区别是:
生产构建
Snowpack 的默认构建输出是未打包的:它将每个文件转换为单独的构建模块,然后将这些模块提供给执行实际绑定的不同“优化器”。这么做的好处是,你可以选择不同终端打包器,以适应不同需求(例如 webpack, Rollup,甚至是 ESbuild),缺点是体验有些支离破碎 —— 例如,esbuild 优化器仍然是不稳定的,Rollup 优化器也不是官方维护,而不同的优化器又有不同的输出和配置。
为了提供更流畅的体验,Vite 选择了与单个打包器(Rollup)进行更深入的集成。Vite 还支持一套 通用插件 API 扩展了 Rollup 的插件接口,开发和构建两种模式都适用。
Vite 支持广泛的功能,构建过程也集成度更高,以下功能目前在 Snowpack 构建优化器中不可用:
- 多页面应用支持
- 库模式
- 自动分割 CSS 代码
- 预优化的异步 chunk 加载
- 自动动态导入 polyfill
- 官方 兼容模式插件 打包为现代/传统两种产物,并根据浏览器支持自动交付正确的版本。
更快的依赖预构建
Vite 使用 esbuild 而不是 Rollup 来进行依赖预构建。这为开发服务器冷启动和依赖项失活的重新构建方面带来了显著的性能改进。
Monorepo 支持
Vite 能够支持 monorepo,我们已经有用户成功地将 Vite 基于 monorepo 模式,与 Yarn, Yarn 2 和 PNPM 使用。
CSS 预处理器支持
Vite 为 Sass and Less 提供了更精细化的支持,包括改进 @import 解析(可使用别名与 npm 依赖)和 提供 url() 内联引入与变基。
Vue 第一优先级支持
Vite 最初是作为 Vue.js 开发工具的未来基础而创建的。尽管 Vite 2.0 版本完全不依赖于框架,但官方 Vue 插件仍然对 Vue 的单文件组件格式提供了一流的支持,涵盖了所有高级特性,如模板资源引用解析、<script setup>,<style module>,自定义块等等。除此之外,Vite 还对 Vue 单文件组件提供了细粒度的 HMR。举个例子,更新一个单文件组件的 <template> 或 <style> 会执行不重置其状态的热更新。
WMR
Preact 团队的 WMR 提供了类似的特性集,而 Vite 2.0 对 Rollup 插件接口的支持正是受到了它的启发。
WMR 主要是为了 Preact 项目而设计,并为其提供了集成度更高的功能,比如预渲染。就使用范围而言,它更加贴合于 Preact 框架,与 Preact 本身一样强调紧凑的大小。如果你正在使用 Preact,那么 WMR 可能会提供更好的体验。然而,WMR 不太可能优先支持其他框架。
@web/dev-server
@web/dev-server(曾经是 es-dev-server)是一个伟大的项目,基于 koa 的 Vite 1.0 开发服务器就是受到了它的启发。
@web/dev-server 适用范围不是很广。它并未提供官方的框架集成,并且需要为生产构建手动设置 Rollup 配置。然而,它的父项目确实提供了一组优秀的 Rollup 插件。
总的来说,与 @web/dev-server 相比,Vite 是一个更注重自身/更高层面的工具,旨在提供开箱即用的工作流。话虽如此,但 @web/dev-server 这个项目群包含了许多其他的优秀工具,也可以使 Vite 用户受益。
3. 从 v1 迁移
配置项变化
- 以下选项已被删除,应通过 插件 实现:
resolverstransformsindexHtmlTransforms
jsx和enableEsbuild都已被删除,请使用新的esbuild选项。- CSS 相关选项 都被包含在
css字段下。 - 所有 用于构建的选项 现在都在
build字段下。rollupInputOptions和rollupOutputOptions已经被build.rollupOptions替代。esbuildTarget现在是build.targetemitManifest现在是build.manifest- 以下构建选项已经被移除,因为它们可以通过插件钩子或其他选项实现:
entryrollupDedupeemitAssetsemitIndexshouldPreloadconfigureBuild
- 所有的 server-specific options 现在都在
server字段下。hostname现在是server.hosthttpsOptions已被删除,server.https可以直接接收选项对象。chokidarWatchOptions现在是server.watch
assetsInclude现在接收string | RegExp | (string | RegExp)[]而不是一个函数。- 所有 Vue 特定选项都已删除;应将选项传递给 Vue 插件。
别名用法变化
alias 现在会被传递给 @rollup/plugin-alias 并不再需要开始/结尾处的斜线了。此行为目前是一个直接替换,所以 1.0 风格的目录别名需要删除其结尾处的斜线:
- alias: { '/@foo/': path.resolve(__dirname, 'some-special-dir') }
+ alias: { '/@foo': path.resolve(__dirname, 'some-special-dir') }
另外,你可以对该选项使用 [{ find: RegExp, replacement: string }] 格式以求更精确的控制。
Vue Support
Vite 2.0 核心已经是框架无关的了。对 Vue 的支持目前详见 @vitejs/plugin-vue。安装它并添加到 Vite 配置十分简单:
import vue from '@vitejs/plugin-vue'
export default {
plugins: [vue()]
}
自定义块转换
一个自定义插件可以用来转换 Vue 自定义块,如下所示:
// vite.config.js
import vue from '@vitejs/plugin-vue'
const vueI18nPlugin = {
name: 'vue-i18n',
transform(code, id) {
if (!/vue&type=i18n/.test(id)) {
return
}
if (/\.ya?ml$/.test(id)) {
code = JSON.stringify(require('js-yaml').safeLoad(code.trim()))
}
return `export default Comp => {
Comp.i18n = ${code}
}`
}
}
export default {
plugins: [vue(), vueI18nPlugin]
}
React 支持
React Fast Refresh 现已支持,详见 @vitejs/plugin-react-refresh。
HMR API 变化
import.meta.hot.acceptDeps() 已经弃用。import.meta.hot.accept() 现在可以接收一个或多个依赖。
Manifest 格式变化
构建清单现在使用以下格式:
{
"index.js": {
"file": "assets/index.acaf2b48.js",
"imports": [...]
},
"index.css": {
"file": "assets/index.7b7dbd85.css"
}
"asset.png": {
"file": "assets/asset.0ab0f9cd.png"
}
}
对于入口 JS chunk,它还列出了它导入的 chunk,这些 chunk 可以用来渲染预加载指令。
写给插件作者
Vite 2 使用了一套完全重定义的,扩展了 Rollup 插件的接口。请阅读新的 插件开发指南.
一些将 v1 插件迁移到 v2 的提示:
resolvers-> 使用resolveId钩子transforms-> 使用transform钩子indexHtmlTransforms-> 使用transformIndexHtml钩子- 虚拟文件支持 -> 使用
resolveId+load钩子 - 添加
alias,define或其他配置项 -> 使用config钩子
由于大多数逻辑应该通过插件钩子而不是中间件来完成,因此对中间件的需求大大减少。内部服务器应用现在是一个很好的旧版的 connect 实例,而不是 Koa。
4. Awesome Vite.js
A curated list of awesome things related to Vite.js
This awesome list is for Vite 2.x and onward. Vite 1.x’s list is archived.
#Resources
#Official Resources
#Get Started
- @vite/create-app - Scaffolding Your First Vite Project.
#Templates
#Vue 3
- Vitesse - Opinionated starter template.
- vite-vue3-tailwind-starter - Vue 3, Vue Router and Tailwind CSS.
- vite-ts-tailwind-starter - TypeScript, Tailwind CSS, Cypress.io e2e tests + CI.
- vite-electron-quick - Starter template with Vue 3, TypeScript and Electron 11.
- vite-electron-builder - Electron apps using Vite for both back and front-end, with automatic releases.
- vue-vben-admin - Background management template based on Vue3, Ant-Design-Vue, TypeScript.
- electron-vue-next - Vue 3 and Electron with VS Code debug and GitHub release process out-of-box.
- vite-wind - Boilerplate with Tailwind CSS, TypeScript, css-pro-layout, 9+ components and dark mode support.
- d2-advance - Boilerplate with Tailwind CSS, TypeScript. Advanced, colorful front-end integration practice.
#Vue 2
- vite-vue2-windicss-starter - Vue 2, Vue Router, Composition API, VueUse, Windi CSS and TypeScript.
- vite-vue2-starter - Barebones Vue 2 starter, similar to Vue-Cli’s base template.
#React
- vite-reactts-electron-starter - React, TailwindCSS, TypeScript and Electron.
- vite-reactts-chakra-starter - React, Typescript, Chakra, Cypress.
- electron-vite-react - Electron, TypeScript and Tailwind CSS with twstyled.
- vite-electron-esbuild-stater - Starter template with React, Typescript, Electron and esbuild.
- Vitamin - React Typescript, TailwindCSS, SPA + PWA, Cypress and CI.
- vite-react-tailwind-rtk - React, Tailwind, Redux Toolkit.
#Svelte
- sttv - Svelte, TailwindCSS, TypeScript.
- svelte-vite-ssr - Svelte with SSR support.
#Plugins
#Framework-agnostic Plugins
#Integrations
- vite-plugin-pwa - Zero-config PWA.
- vite-plugin-purge-icons - Bundle icons on demand by PurgeIcons.
- vite-eslint - Allow ESLint to work with bundling and dev server.
- vite-plugin-windicss - Windi CSS integration.
- vite-plugin-node - Integration with Node.js backend servers.
- vite-plugin-cesium - Integration with Cesium library.
- vite-plugin-mpa - Out-of-box multi-page application (MPA) integration.
- vite-plugin-svg-icons - Fast creating SVG sprites.
#Loaders
- vite-plugin-rsw - Load rust-compiled (wasm-pack) WebAssembly packages.
- vite-plugin-fonts - Webfont loader.
- vite-imagetools - Load and transform images using url query parameters.
- vite-plugin-radar - All in one analytics loader (with 7+ providers supported).
#Bundling
- vite-plugin-compress - Compress your bundle + assets.
- vite-plugin-imagemin - Compress image assets.
- vite-plugin-importer - Integration for babel-plugin-import.
- vite-plugin-banner - Adds a banner to the top of each generated chunk.
- vite-plugin-compression - Use gzip or brotli to compress resources.
#Transformers
- vite-plugin-html - Plugin to minimize and use ejs template syntax in
index.html. - vite-plugin-ts-nameof - Ability to resolve nameof in TypeScript.
- vite-plugin-handlebars - Process HTML files with Handlebars.
#Helpers
- vite-tsconfig-paths - Support for TypeScript’s path mapping.
- vite-plugin-faker - Use TypeScript compiler to generate mock data.
- vite-plugin-style-import - Introduces component library styles on demand.
- vite-plugin-mock - Mock plugin for development and production.
- vite-plugin-mocker - Mocker server.
- vite-plugin-theme - Dynamically changing the theme color.
- vite-plugin-test - Headless testing your component.
- vite-aliases - Alias auto-generation based on project structure.
- vite-plugin-import - Modular import plugin for Vite.
- vite-plugin-imp - Import library component styles on demand, make your app slimmer.
#Vue
In this section, we use badges to indicate the targeted Vue version for each plugin.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qbkHfBZB-1635318954315)(https://img.shields.io/badge/-v2-42b883)] for Vue 2 only, [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GNiMOImV-1635318954317)(https://img.shields.io/badge/-v3-35495e)] for Vue 3 only, and [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t30Sq9PG-1635318954318)(https://img.shields.io/badge/-2%2F3-3C8171)] for plugins that compatible with both versions.
#Integrations
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sQMtdTRJ-1635318954322)(https://img.shields.io/badge/-v3-35495e)] @vitejs/plugin-vue - Official Vue 3 support.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E2qNVyzB-1635318954323)(https://img.shields.io/badge/-v2-42b883)] vite-plugin-vue2 - Vue 2 integration.
#Routing
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4qcz7kr7-1635318954324)(https://img.shields.io/badge/-2%2F3-3C8171)] vite-plugin-voie - File system based routing.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fAsKTRKY-1635318954325)(https://img.shields.io/badge/-2%2F3-3C8171)] vite-plugin-pages - File system based route generator.
#Loaders
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5J28RoFC-1635318954326)(https://img.shields.io/badge/-2%2F3-3C8171)] vite-plugin-md - Markdown as Vue components / Vue components in Markdown.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OLyPexiZ-1635318954327)(https://img.shields.io/badge/-2%2F3-3C8171)] vite-plugin-icons - Access thousands of icons as Vue components.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kTxg4Ed4-1635318954328)(https://img.shields.io/badge/-v3-35495e)] vite-plugin-vuedoc - Markdown Code block as Vue Preview components.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2U042rdU-1635318954329)(https://img.shields.io/badge/-v3-35495e)] vite-svg-loader - Load SVG files as Vue components.
#SSR / SSG
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zVTHzAux-1635318954330)(https://img.shields.io/badge/-v3-35495e)] vite-ssg - Server-side generation.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B1l6GN0W-1635318954331)(https://img.shields.io/badge/-v3-35495e)] vite-ssr - Server-side rendering.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oLVmmqKi-1635318954332)(https://img.shields.io/badge/-v3-35495e)] vitedge - Edge-side rendering with fullstack utilities.
#Ecosystem
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YuJHmhnv-1635318954332)(https://img.shields.io/badge/-v3-35495e)] vite-plugin-vue-i18n - Integration for Vue I18n.
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fdkTyQIN-1635318954333)(https://img.shields.io/badge/-v3-35495e)] vite-plugin-i18n-resources - Load i18n translation message files.
#Helpers
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DkxafYqW-1635318954334)(https://img.shields.io/badge/-2%2F3-3C8171)] vite-plugin-components - On-demand components auto-importing.
#Bundling
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UX0F5iyg-1635318954335)(https://img.shields.io/badge/-v3-35495e)] vite-plugin-multi-device - Outputs for different devices.
#React
#Official
- @vitejs/plugin-react-refresh - Official React Refresh support.
#Loaders
- vite-plugin-svgr - Transform SVGs into React components.
- vite-plugin-mdx - Use MDX for your Vite app, with support for MDX v1, MDX v2, HMR, and SSR.
#Transformers
- vite-plugin-twstyled - Plugin to compile Tailwind CSS with JSX and CSS-in-JS support.
#Framework
- vite-plugin-react-pages - A Vite framework for building React app.
#Solid
#Integrations
- vite-plugin-solid - Provides JSX transformation for Solid.
#Rollup Plugins
- Vite Rollup Plugins - Compatibility list for official rollup plugins.
#Included in Vite
- @rollup/plugin-alias - Define and resolve aliases for bundle dependencies.
- @rollup/plugin-commonjs - Convert CommonJS modules to ES6.
- @rollup/plugin-dynamic-import-vars - Resolving dynamic imports that contain variables.
- @rollup/plugin-json - Convert
.jsonfiles to ES6 modules.
#Covered by default in Vite
- @rollup/plugin-babel - Compile your files with Babel.
- @rollup/plugin-buble - Compile ES2015 with buble.
- @rollup/plugin-data-uri - Import modules from Data URIs.
- @rollup/plugin-html - Create HTML files to serve Rollup bundles.
- @rollup/plugin-node-resolve - Locate and bundle third-party dependencies in node_modules.
- @rollup/plugin-sucrase - Compile TypeScript, Flow, JSX, etc with Sucrase.
- @rollup/plugin-typescript - Integration between Rollup and Typescript.
- @rollup/plugin-wasm - Import WebAssembly code with Rollup.
- @rollup/plugin-url - Import files as data-URIs or ES Modules.
#Compatible with Vite
- @rollup/plugin-beep - System beeps on errors and warnings.
- @rollup/plugin-dsv - Convert
.csvand.tsvfiles into JavaScript modules with d3-dsv. - @rollup/plugin-eslint - Verify entry point and all imported files with ESLint.
- @rollup/plugin-graphql - Convert .gql/.graphql files to ES6 modules.
- @rollup/plugin-image - Import JPG, PNG, GIF, SVG, and WebP files (needs
enforce: 'pre'). - @rollup/plugin-inject - Scan modules for global variables and injects import statements where necessary.
- @rollup/plugin-legacy - Add export declarations to legacy non-module scripts.
- @rollup/plugin-replace - Replace strings in files while bundling.
- @rollup/plugin-strip - Remove debugger statements and functions from your code.
- @rollup/plugin-virtual - A Rollup plugin which loads virtual modules from memory.
- @rollup/plugin-yaml - Convert YAML files to ES6 modules.
#Community
- Check the Awesome Rollup list for community maintained rollup plugins, and refer to the Vite docs section about rollup plugin compatibility.
#Integrations with Backends
#Ruby on Rails
- Vite Ruby - Integration for Rails, Hanami, Padrino, and Rack apps.
- vite-plugin-ruby - Configuration for Ruby backends.
#Migrations
#Vue CLI
- vue-cli-plugin-vite - Use Vite on Vue CLI with minimize codebase modifications.
#Projects Using Vite.js
#Open Source
- VitePress - Static Site Generator powered by Vite and Vue.
- TroisJS - Three.js integration with Vite and Vue 3.
#Apps/Websites
- Icônes - Icon explorer with instant search.
- Awesome CN Café - Web application for Awesome CN Café.
- Todo Example - Todo app with routing and state management.
- Tailwind Pre-Processor - An implementation of Tailwind CSS using Less / Stylus / Sass / SCSS.
- npmview - A web application to view npm package files.
- Layoutit Grid - Interactive CSS Grid layout generator.
- TypGame - Test your typing performance.
- aitrack.work - A task-based time tracker for everyday use.
- macOS Web - macOS Desktop experience for Web.