+
+
+
diff --git a/docs/.vitepress/theme/components/blog.data.ts b/docs/.vitepress/theme/components/blog.data.ts
new file mode 100644
index 00000000000000..39d45ec2b2b1a2
--- /dev/null
+++ b/docs/.vitepress/theme/components/blog.data.ts
@@ -0,0 +1,40 @@
+import { createContentLoader } from 'vitepress'
+
+interface Post {
+ title: string
+ url: string
+ date: {
+ time: number
+ string: string
+ }
+}
+
+declare const data: Post[]
+export { data }
+
+export default createContentLoader('blog/*.md', {
+ // excerpt: true,
+ transform(raw): Post[] {
+ return raw
+ .map(({ url, frontmatter }) => ({
+ title: frontmatter.head.find((e) => e[1].property === 'og:title')[1]
+ .content,
+ url,
+ date: formatDate(frontmatter.date),
+ }))
+ .sort((a, b) => b.date.time - a.date.time)
+ },
+})
+
+function formatDate(raw: string): Post['date'] {
+ const date = new Date(raw)
+ date.setUTCHours(12)
+ return {
+ time: +date,
+ string: date.toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ }),
+ }
+}
diff --git a/docs/.vitepress/theme/composables/sponsor.ts b/docs/.vitepress/theme/composables/sponsor.ts
index 4fd12e5facb1ee..622252593f7027 100644
--- a/docs/.vitepress/theme/composables/sponsor.ts
+++ b/docs/.vitepress/theme/composables/sponsor.ts
@@ -1,4 +1,4 @@
-import { ref, onMounted } from 'vue'
+import { onMounted, onUnmounted, ref } from 'vue'
interface Sponsors {
special: Sponsor[]
@@ -13,6 +13,10 @@ interface Sponsor {
name: string
img: string
url: string
+ /**
+ * Expects to also have an **inversed** image with `-dark` postfix.
+ */
+ hasDark?: true
}
// shared data across instances so we load only once.
@@ -49,11 +53,59 @@ const viteSponsors: Pick = {
url: 'https://remix.run/',
img: '/remix.svg',
},
+ {
+ name: 'Nx',
+ url: 'https://nx.dev/',
+ img: '/nx.svg',
+ },
+ {
+ name: 'Transloadit',
+ url: 'https://transloadit.com/?utm_source=vite&utm_medium=referral&utm_campaign=sponsorship&utm_content=website',
+ img: '/transloadit.svg',
+ hasDark: true,
+ },
+ {
+ name: 'Huly',
+ url: 'https://huly.io/',
+ img: '/huly.svg',
+ },
+ {
+ name: 'Handsontable',
+ url: 'https://handsontable.com/docs/react-data-grid/?utm_source=vite_docs&utm_medium=sponsorship&utm_campaign=library_sponsorship_2024',
+ img: '/handsontable.svg',
+ },
],
}
+function toggleDarkLogos() {
+ if (data.value) {
+ const isDark = document.documentElement.classList.contains('dark')
+ data.value.forEach(({ items }) => {
+ items.forEach((s: Sponsor) => {
+ if (s.hasDark) {
+ s.img = isDark
+ ? s.img.replace(/(\.\w+)$/, '-dark$1')
+ : s.img.replace(/-dark(\.\w+)$/, '$1')
+ }
+ })
+ })
+ }
+}
+
export function useSponsor() {
onMounted(async () => {
+ const ob = new MutationObserver((list) => {
+ for (const m of list) {
+ if (m.attributeName === 'class') {
+ toggleDarkLogos()
+ }
+ }
+ })
+ ob.observe(document.documentElement, { attributes: true })
+ onUnmounted(() => {
+ ob.disconnect()
+ })
+
if (data.value) {
return
}
@@ -62,6 +114,7 @@ export function useSponsor() {
const json = await result.json()
data.value = mapSponsors(json)
+ toggleDarkLogos()
})
return {
@@ -84,7 +137,7 @@ function mapSponsors(sponsors: Sponsors) {
{
tier: 'Gold Sponsors',
size: 'medium',
- items: viteSponsors['gold'].concat(mapImgPath(sponsors['gold'])),
+ items: [...mapImgPath(sponsors['gold']), ...viteSponsors['gold']],
},
]
}
diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts
index a85c67e1df22f5..5fa0d638a3f9a1 100644
--- a/docs/.vitepress/theme/index.ts
+++ b/docs/.vitepress/theme/index.ts
@@ -1,6 +1,8 @@
import { h } from 'vue'
import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
+import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client'
+import '@shikijs/vitepress-twoslash/style.css'
import './styles/vars.css'
import HomeSponsors from './components/HomeSponsors.vue'
import AsideSponsors from './components/AsideSponsors.vue'
@@ -16,5 +18,6 @@ export default {
},
enhanceApp({ app }) {
app.component('SvgImage', SvgImage)
+ app.use(TwoslashFloatingVue)
},
} satisfies Theme
diff --git a/docs/.vitepress/theme/styles/vars.css b/docs/.vitepress/theme/styles/vars.css
index 58e5e79ff0f703..645a1e9222d613 100644
--- a/docs/.vitepress/theme/styles/vars.css
+++ b/docs/.vitepress/theme/styles/vars.css
@@ -118,3 +118,19 @@
.vp-sponsor.aside .vp-sponsor-grid.mini .vp-sponsor-grid-image {
max-width: 124px;
}
+
+.vp-sponsor-grid.big .vp-sponsor-grid-image {
+ max-height: 96px;
+}
+
+.vp-sponsor-grid.mini .vp-sponsor-grid-image[alt='Bit'] {
+ max-height: 48px;
+}
+
+.vp-sponsor-grid.xmini .vp-sponsor-grid-image[alt='JetBrains'] {
+ max-height: 54px;
+}
+
+.vp-sponsor-grid.medium .vp-sponsor-grid-image[alt='JetBrains'] {
+ max-height: 100px;
+}
diff --git a/docs/.vitepress/tsconfig.json b/docs/.vitepress/tsconfig.json
new file mode 100644
index 00000000000000..20b9618d576e3e
--- /dev/null
+++ b/docs/.vitepress/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "strict": true,
+ "noImplicitOverride": true,
+ "noUnusedLocals": true,
+ "esModuleInterop": true,
+ "noEmit": true
+ },
+ "exclude": ["cache", "dist"]
+}
diff --git a/docs/_data/team.js b/docs/_data/team.js
index 72641a597cee55..a58e4cabf42935 100644
--- a/docs/_data/team.js
+++ b/docs/_data/team.js
@@ -22,6 +22,7 @@ export const core = [
links: [
{ icon: 'github', link: 'https://github.com/patak-dev' },
{ icon: 'twitter', link: 'https://twitter.com/patak_dev' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@patak' },
],
sponsor: 'https://github.com/sponsors/patak-dev',
},
@@ -35,6 +36,7 @@ export const core = [
links: [
{ icon: 'github', link: 'https://github.com/antfu' },
{ icon: 'twitter', link: 'https://twitter.com/antfu7' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@antfu' },
],
sponsor: 'https://github.com/sponsors/antfu',
},
@@ -46,6 +48,7 @@ export const core = [
links: [
{ icon: 'github', link: 'https://github.com/bluwy' },
{ icon: 'twitter', link: 'https://twitter.com/bluwyoo' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@bluwy' },
],
sponsor: 'https://bjornlu.com/sponsor',
},
@@ -53,25 +56,48 @@ export const core = [
avatar: 'https://github.com/sapphi-red.png',
name: 'green',
title: 'Web Developer',
- desc: 'Vite team member. Call me sapphi or green or midori ;)',
+ desc: 'Vite core team member. Call me sapphi or green or midori ;)',
links: [
{ icon: 'github', link: 'https://github.com/sapphi-red' },
{ icon: 'twitter', link: 'https://twitter.com/sapphi_red' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@sapphi_red' },
],
sponsor: 'https://github.com/sponsors/sapphi-red',
},
{
- avatar: 'https://github.com/sodatea.png',
- name: 'Haoqun Jiang',
- title: 'Developer',
- org: 'Vue.js',
- orgLink: 'https://vuejs.org/',
- desc: 'Vue/Vite core team member. Full-time open sourcerer.',
+ avatar: 'https://github.com/ArnaudBarre.png',
+ name: 'Arnaud Barré',
+ title: 'Frontend Developer',
+ desc: 'Passionate by tooling around TypeScript and React.',
links: [
- { icon: 'github', link: 'https://github.com/sodatea' },
- { icon: 'twitter', link: 'https://twitter.com/haoqunjiang' },
+ { icon: 'github', link: 'https://github.com/ArnaudBarre' },
+ { icon: 'twitter', link: 'https://twitter.com/_ArnaudBarre' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@ArnaudBarre' },
],
- sponsor: 'https://github.com/sponsors/sodatea',
+ sponsor: 'https://github.com/sponsors/ArnaudBarre',
+ },
+ {
+ avatar: 'https://github.com/dominikg.png',
+ name: 'Dominik G.',
+ title: 'Resident CI Expert',
+ desc: 'Team Member of Vite and Svelte',
+ links: [
+ { icon: 'github', link: 'https://github.com/dominikg' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@dominikg' },
+ ],
+ sponsor: 'https://github.com/sponsors/dominikg',
+ },
+ {
+ avatar: 'https://github.com/sheremet-va.png',
+ name: 'Vladimir',
+ title: 'Core team member of Vitest & Vite',
+ desc: 'An open source fullstack developer',
+ links: [
+ { icon: 'github', link: 'https://github.com/sheremet-va' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@sheremet_va' },
+ { icon: 'twitter', link: 'https://twitter.com/sheremet_va' },
+ ],
+ sponsor: 'https://github.com/sponsors/sheremet-va',
},
{
avatar: 'https://github.com/Shinigami92.png',
@@ -82,10 +108,27 @@ export const core = [
desc: 'Passionate TypeScript enthusiast working extensively with Vue SPA and pug.',
links: [
{ icon: 'github', link: 'https://github.com/Shinigami92' },
- { icon: 'twitter', link: 'https://twitter.com/Shini_92' },
+ { icon: 'mastodon', link: 'https://elk.zone/mas.to/@Shini92' },
],
sponsor: 'https://github.com/sponsors/Shinigami92',
},
+ {
+ avatar: 'https://github.com/sodatea.png',
+ name: 'Haoqun Jiang',
+ title: 'Developer',
+ org: 'Vue.js',
+ orgLink: 'https://vuejs.org/',
+ desc: 'Vue/Vite core team member. Full-time open sourcerer.',
+ links: [
+ { icon: 'github', link: 'https://github.com/sodatea' },
+ { icon: 'twitter', link: 'https://twitter.com/haoqunjiang' },
+ { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@haoqun' },
+ ],
+ sponsor: 'https://github.com/sponsors/sodatea',
+ },
+]
+
+export const emeriti = [
{
avatar: 'https://i.imgur.com/KMed6rQ.jpeg',
name: 'Alec Larson',
@@ -95,7 +138,6 @@ export const core = [
{ icon: 'github', link: 'https://github.com/aleclarson' },
{ icon: 'twitter', link: 'https://twitter.com/retropragma' },
],
- sponsor: 'https://github.com/sponsors/aleclarson',
},
{
avatar: 'https://github.com/poyoho.png',
@@ -107,40 +149,6 @@ export const core = [
{ icon: 'twitter', link: 'https://twitter.com/yoho_po' },
],
},
- {
- avatar: 'https://github.com/ArnaudBarre.png',
- name: 'Arnaud Barré',
- title: 'Frontend Developer',
- desc: 'Passionate by tooling around TypeScript and React.',
- links: [{ icon: 'github', link: 'https://github.com/ArnaudBarre' }],
- sponsor: 'https://github.com/sponsors/ArnaudBarre',
- },
- {
- avatar: 'https://github.com/dominikg.png',
- name: 'Dominik G.',
- title: 'Resident CI Expert',
- desc: 'Team Member of Vite and Svelte',
- links: [
- { icon: 'github', link: 'https://github.com/dominikg' },
- { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@dominikg' },
- ],
- sponsor: 'https://github.com/sponsors/dominikg',
- },
- {
- avatar: 'https://github.com/sheremet-va.png',
- name: 'Vladimir',
- title: 'Core team member of Vitest & Vite',
- desc: 'An open source fullstack developer',
- links: [
- { icon: 'github', link: 'https://github.com/sheremet-va' },
- { icon: 'mastodon', link: 'https://elk.zone/m.webtoo.ls/@sheremet_va' },
- { icon: 'twitter', link: 'https://twitter.com/sheremet_va' },
- ],
- sponsor: 'https://github.com/sponsors/sheremet-va',
- },
-]
-
-export const emeriti = [
{
avatar: 'https://github.com/ygj6.png',
name: 'ygj6',
diff --git a/docs/blog.md b/docs/blog.md
new file mode 100644
index 00000000000000..f3f8c6298284b1
--- /dev/null
+++ b/docs/blog.md
@@ -0,0 +1,13 @@
+---
+sidebar: false
+editLink: false
+outline: false
+---
+
+
+
+# Latest From the Vite Blog
+
+
diff --git a/docs/blog/announcing-vite2.md b/docs/blog/announcing-vite2.md
index d81debc9b38d69..11cd6d52307812 100644
--- a/docs/blog/announcing-vite2.md
+++ b/docs/blog/announcing-vite2.md
@@ -1,5 +1,22 @@
---
+title: Announcing Vite 2.0
+author:
+ - name: The Vite Team
sidebar: false
+date: 2021-02-16
+head:
+ - - meta
+ - property: og:type
+ content: website
+ - - meta
+ - property: og:title
+ content: Announcing Vite 2.0
+ - - meta
+ - property: og:url
+ content: https://vitejs.dev/blog/announcing-vite2
+ - - meta
+ - property: og:description
+ content: Vite 2 Release Announcement
---
# Announcing Vite 2.0
diff --git a/docs/blog/announcing-vite3.md b/docs/blog/announcing-vite3.md
index dba46bb8a05981..4f25309ca72f04 100644
--- a/docs/blog/announcing-vite3.md
+++ b/docs/blog/announcing-vite3.md
@@ -1,4 +1,8 @@
---
+title: Vite 3.0 is out!
+author:
+ name: The Vite Team
+date: 2022-07-23
sidebar: false
head:
- - meta
@@ -25,7 +29,7 @@ head:
_July 23, 2022_ - Check out the [Vite 4.0 announcement](./announcing-vite4.md)
-In February last year, [Evan You](https://twitter.com/youyuxi) released Vite 2. Since then, its adoption has grown non-stop, reaching more than 1 million npm downloads per week. A sprawling ecosystem rapidly formed after the release. Vite is powering a renewed innovation race in Web frameworks. [Nuxt 3](https://v3.nuxtjs.org/) uses Vite by default. [SvelteKit](https://kit.svelte.dev/), [Astro](https://astro.build/), [Hydrogen](https://hydrogen.shopify.dev/), and [SolidStart](https://docs.solidjs.com/start) are all built with Vite. [Laravel has now decided to use Vite by default](https://laravel.com/docs/9.x/vite). [Vite Ruby](https://vite-ruby.netlify.app/) shows how Vite can improve Rails DX. [Vitest](https://vitest.dev) is making strides as a Vite-native alternative to Jest. Vite is behind [Cypress](https://docs.cypress.io/guides/component-testing/writing-your-first-component-test) and [Playwright](https://playwright.dev/docs/test-components)'s new Component Testing features, Storybook has [Vite as an official builder](https://github.com/storybookjs/builder-vite). And [the list goes on](https://patak.dev/vite/ecosystem.html). Maintainers from most of these projects got involved in improving the Vite core itself, working closely with the Vite [team](https://vitejs.dev/team) and other contributors.
+In February last year, [Evan You](https://twitter.com/youyuxi) released Vite 2. Since then, its adoption has grown non-stop, reaching more than 1 million npm downloads per week. A sprawling ecosystem rapidly formed after the release. Vite is powering a renewed innovation race in Web frameworks. [Nuxt 3](https://v3.nuxtjs.org/) uses Vite by default. [SvelteKit](https://kit.svelte.dev/), [Astro](https://astro.build/), [Hydrogen](https://hydrogen.shopify.dev/), and [SolidStart](https://docs.solidjs.com/quick-start) are all built with Vite. [Laravel has now decided to use Vite by default](https://laravel.com/docs/9.x/vite). [Vite Ruby](https://vite-ruby.netlify.app/) shows how Vite can improve Rails DX. [Vitest](https://vitest.dev) is making strides as a Vite-native alternative to Jest. Vite is behind [Cypress](https://docs.cypress.io/guides/component-testing/writing-your-first-component-test) and [Playwright](https://playwright.dev/docs/test-components)'s new Component Testing features, Storybook has [Vite as an official builder](https://github.com/storybookjs/builder-vite). And [the list goes on](https://patak.dev/vite/ecosystem.html). Maintainers from most of these projects got involved in improving the Vite core itself, working closely with the Vite [team](https://vitejs.dev/team) and other contributors.
![Vite 3 Announcement Cover Image](/og-image-announcing-vite3.png)
diff --git a/docs/blog/announcing-vite4-3.md b/docs/blog/announcing-vite4-3.md
index 756c3579d1bed0..534a2fdcb41bd6 100644
--- a/docs/blog/announcing-vite4-3.md
+++ b/docs/blog/announcing-vite4-3.md
@@ -1,4 +1,8 @@
---
+title: Vite 4.3 is out!
+author:
+ name: The Vite Team
+date: 2023-04-20
sidebar: false
head:
- - meta
diff --git a/docs/blog/announcing-vite4.md b/docs/blog/announcing-vite4.md
index 950ac637a3c902..587d439733ab38 100644
--- a/docs/blog/announcing-vite4.md
+++ b/docs/blog/announcing-vite4.md
@@ -1,4 +1,8 @@
---
+title: Vite 4.0 is out!
+author:
+ name: The Vite Team
+date: 2022-12-09
sidebar: false
head:
- - meta
@@ -23,7 +27,7 @@ head:
# Vite 4.0 is out!
-_December 9, 2022_
+_December 9, 2022_ - Check out the [Vite 5.0 announcement](./announcing-vite5.md)
Vite 3 [was released](./announcing-vite3.md) five months ago. npm downloads per week have gone from 1 million to 2.5 million since then. The ecosystem has matured too, and continues to grow. In this year's [Jamstack Conf survey](https://twitter.com/vite_js/status/1589665610119585793), usage among the community jumped from 14% to 32% while keeping a high 9.7 satisfaction score. We saw the stable releases of [Astro 1.0](https://astro.build/), [Nuxt 3](https://v3.nuxtjs.org/), and other Vite-powered frameworks that are innovating and collaborating: [SvelteKit](https://kit.svelte.dev/), [Solid Start](https://www.solidjs.com/blog/introducing-solidstart), [Qwik City](https://qwik.builder.io/qwikcity/overview/). Storybook announced first-class support for Vite as one of its main features for [Storybook 7.0](https://storybook.js.org/blog/first-class-vite-support-in-storybook/). Deno now [supports Vite](https://www.youtube.com/watch?v=Zjojo9wdvmY). [Vitest](https://vitest.dev) adoption is exploding, it will soon represent half of Vite's npm downloads. Nx is also investing in the ecosystem, and [officially supports Vite](https://nx.dev/packages/vite).
@@ -38,7 +42,7 @@ Today, the Vite [team](https://vitejs.dev/team) with the help of our ecosystem p
Quick links:
- [Docs](/)
-- [Migration Guide](/guide/migration)
+- [Migration Guide](https://v4.vitejs.dev/guide/migration.html)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#400-2022-12-09)
Docs in other languages:
@@ -87,7 +91,7 @@ This double loading could occur since a `.css` file will be emitted and it's lik
import stuff from './global.css?inline'
```
-Learn more in the [Migration Guide](/guide/migration).
+Learn more in the [Migration Guide](https://v4.vitejs.dev/guide/migration.html).
## Environment Variables
diff --git a/docs/blog/announcing-vite5-1.md b/docs/blog/announcing-vite5-1.md
new file mode 100644
index 00000000000000..35ee61c172870e
--- /dev/null
+++ b/docs/blog/announcing-vite5-1.md
@@ -0,0 +1,132 @@
+---
+title: Vite 5.1 is out!
+author:
+ name: The Vite Team
+date: 2024-02-08
+sidebar: false
+head:
+ - - meta
+ - property: og:type
+ content: website
+ - - meta
+ - property: og:title
+ content: Announcing Vite 5.1
+ - - meta
+ - property: og:image
+ content: https://vitejs.dev/og-image-announcing-vite5-1.png
+ - - meta
+ - property: og:url
+ content: https://vitejs.dev/blog/announcing-vite5-1
+ - - meta
+ - property: og:description
+ content: Vite 5.1 Release Announcement
+ - - meta
+ - name: twitter:card
+ content: summary_large_image
+---
+
+# Vite 5.1 is out!
+
+_February 8, 2024_
+
+![Vite 5.1 Announcement Cover Image](/og-image-announcing-vite5-1.png)
+
+Vite 5 [was released](./announcing-vite5.md) last November, and it represented another big leap for Vite and the ecosystem. A few weeks ago we celebrated 10 million weekly npm downloads and 900 contributors to the Vite repo. Today, we're excited to announce the release of Vite 5.1.
+
+Quick links: [Docs](/), [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#510-2024-02-08)
+
+Docs in other languages: [简体中文](https://cn.vitejs.dev/), [日本語](https://ja.vitejs.dev/), [Español](https://es.vitejs.dev/), [Português](https://pt.vitejs.dev/), [한국어](https://ko.vitejs.dev/), [Deutsch](https://de.vitejs.dev/)
+
+Try Vite 5.1 online in StackBlitz: [vanilla](https://vite.new/vanilla-ts), [vue](https://vite.new/vue-ts), [react](https://vite.new/react-ts), [preact](https://vite.new/preact-ts), [lit](https://vite.new/lit-ts), [svelte](https://vite.new/svelte-ts), [solid](https://vite.new/solid-ts), [qwik](https://vite.new/qwik-ts).
+
+If you're new to Vite, we suggest reading first the [Getting Started](/guide/) and [Features](/guide/features) guides.
+
+To stay up to date, follow us on [X](https://x.com/vite_js) or [Mastodon](https://webtoo.ls/@vite).
+
+## Vite Runtime API
+
+Vite 5.1 adds experimental support for a new Vite Runtime API. It allows running any code by processing it with Vite plugins first. It is different from `server.ssrLoadModule` because the runtime implementation is decoupled from the server. This lets library and framework authors implement their own layer of communication between the server and the runtime. This new API is intended to replace Vite's current SSR primitives once it is stable.
+
+The new API brings many benefits:
+
+- Support for HMR during SSR.
+- It is decoupled from the server, so there is no limit on how many clients can use a single server - every client has its own module cache (you can even communicate with it how you want - using message channel/fetch call/direct function call/websocket).
+- It doesn't depend on any node/bun/deno built-in APIs, so it can run in any environment.
+- It's easy to integrate with tools that have their own mechanism to run code (you can provide a runner to use `eval` instead of `new AsyncFunction` for example).
+
+The initial idea [was proposed by Pooya Parsa](https://github.com/nuxt/vite/pull/201) and implemented by [Anthony Fu](https://github.com/antfu) as the [vite-node](https://github.com/vitest-dev/vitest/tree/main/packages/vite-node#readme) package to [power Nuxt 3 Dev SSR](https://antfu.me/posts/dev-ssr-on-nuxt) and later also used as the base for [Vitest](https://vitest.dev). So the general idea of vite-node has been battle-tested for quite some time now. This is a new iteration of the API by [Vladimir Sheremet](https://github.com/sheremet-va), who had already re-implemented vite-node in Vitest and took the learnings to make the API even more powerful and flexible when adding it to Vite Core. The PR was one year in the makings, you can see the evolution and discussions with ecosystem maintainers [here](https://github.com/vitejs/vite/issues/12165).
+
+Read more in the [Vite Runtime API guide](/guide/api-vite-runtime) and [give us feedback](https://github.com/vitejs/vite/discussions/15774).
+
+## Features
+
+### Improved support for `.css?url`
+
+Import CSS files as URLs now works reliably and correctly. This was the last remaining hurdle in Remix's move to Vite. See ([#15259](https://github.com/vitejs/vite/issues/15259)).
+
+### `build.assetsInlineLimit` now supports a callback
+
+Users can now [provide a callback](/config/build-options.html#build-assetsinlinelimit) that returns a boolean to opt-in or opt-out of inlining for specific assets. If `undefined` is returned, the default logic applies. See ([#15366](https://github.com/vitejs/vite/issues/15366)).
+
+### Improved HMR for circular import
+
+In Vite 5.0, accepted modules within circular imports always triggered a full page reload even if they can be handled fine in the client. This is now relaxed to allow HMR to apply without a full page reload, but if any error happens during HMR, the page will be reloaded. See ([#15118](https://github.com/vitejs/vite/issues/15118)).
+
+### Support `ssr.external: true` to externalize all SSR packages
+
+Historically, Vite externalizes all packages except for linked packages. This new option can be used to force externalize all packages including linked packages too. This is handy in tests within monorepos where we want to emulate the usual case of all packages externalized, or when using `ssrLoadModule` to load an arbitrary file and we want to always external packages as we don't care about HMR. See ([#10939](https://github.com/vitejs/vite/issues/10939)).
+
+### Expose `close` method in the preview server
+
+The preview server now exposes a `close` method, which will properly teardown the server including all opened socket connections. See ([#15630](https://github.com/vitejs/vite/issues/15630)).
+
+## Performance improvements
+
+Vite keeps getting faster with each release, and Vite 5.1 is packed with performance improvements. We measured the loading time for 10K modules (25 level deep tree) using [vite-dev-server-perf](https://github.com/yyx990803/vite-dev-server-perf) for all minor versions from Vite 4.0. This is a good benchmark to measure the effect of Vite's bundle-less approach. Each module is a small TypeScript file with a counter and imports to other files in the tree, so this mostly measuring the time it takes to do the requests a separate modules. In Vite 4.0, loading 10K modules took 8 seconds on a M1 MAX. We had a breakthrough in [Vite 4.3 were we focused on performance](./announcing-vite4-3.md), and we were able to load them in 6.35 seconds. In Vite 5.1, we managed to do another performance leap. Vite is now serving the 10K modules in 5.35 seconds.
+
+![Vite 10K Modules Loading time progression](/vite5-1-10K-modules-loading-time.png)
+
+The results of this benchmark run on Headless Puppeteer and are a good way to compare versions. They don't represent the time as experienced by users though. When running the same 10K modules in an Incognito window is Chrome, we have:
+
+| 10K Modules | Vite 5.0 | Vite 5.1 |
+| --------------------- | :------: | :------: |
+| Loading time | 2892ms | 2765ms |
+| Loading time (cached) | 2778ms | 2477ms |
+| Full reload | 2003ms | 1878ms |
+| Full reload (cached) | 1682ms | 1604ms |
+
+### Run CSS preprocessors in threads
+
+Vite now has opt-in support for running CSS preprocessors in threads. You can enable it using [`css.preprocessorMaxWorkers: true`](/config/shared-options.html#css-preprocessormaxworkers). For a Vuetify 2 project, dev startup time was reduced by 40% with this feature enabled. There is [performance comparison for others setups in the PR](https://github.com/vitejs/vite/pull/13584#issuecomment-1678827918). See ([#13584](https://github.com/vitejs/vite/issues/13584)). [Give Feedback](https://github.com/vitejs/vite/discussions/15835).
+
+### New options to improve server cold starts
+
+You can set `optimizeDeps.holdUntilCrawlEnd: false` to switch to a new strategy for deps optimization that may help in big projects. We're considering switching to this strategy by default in the future. [Give Feedback](https://github.com/vitejs/vite/discussions/15834). ([#15244](https://github.com/vitejs/vite/issues/15244))
+
+### Faster resolving with cached checks
+
+The `fs.cachedChecks` optimization is now enabled by default. In Windows, `tryFsResolve` was ~14x faster with it, and resolving ids overall got a ~5x speed up in the triangle benchmark. ([#15704](https://github.com/vitejs/vite/issues/15704))
+
+### Internal performance improvements
+
+The dev server had several incremental performance gains. A new middleware to short-circuit on 304 ([#15586](https://github.com/vitejs/vite/issues/15586)). We avoided `parseRequest` in hot paths ([#15617](https://github.com/vitejs/vite/issues/15617)). Rollup is now properly lazy loaded ([#15621](https://github.com/vitejs/vite/issues/15621))
+
+## Deprecations
+
+We continue to reduce Vite's API surface where possible to make the project maintainable long term.
+
+### Deprecated `as` option in `import.meta.glob`
+
+The standard moved to [Import Attributes](https://github.com/tc39/proposal-import-attributes), but we don't plan to replace `as` with a new option at this point. Instead, it is recommended that the user switches to `query`. See ([#14420](https://github.com/vitejs/vite/issues/14420)).
+
+### Removed experimental build-time pre-bundling
+
+Build-time pre-bundling, an experimental feature added in Vite 3, is removed. With Rollup 4 switching its parser to native, and Rolldown being worked on, both the performance and the dev-vs-build inconsistency story for this feature are no longer valid. We want to continue improving dev/build consistency, and have concluded that using Rolldown for "prebundling during dev" and "production builds" is the better bet moving forward. Rolldown may also implement caching in a way that is a lot more efficient during build than deps prebundling. See ([#15184](https://github.com/vitejs/vite/issues/15184)).
+
+## Get Involved
+
+We are grateful to the [900 contributors to Vite Core](https://github.com/vitejs/vite/graphs/contributors), and the maintainers of plugins, integrations, tools, and translations that keeps pushing the ecosystem forward. If you're enjoying Vite, we invite you to participate and help us. Check out our [Contributing Guide](https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md), and jump into [triaging issues](https://github.com/vitejs/vite/issues), [reviewing PRs](https://github.com/vitejs/vite/pulls), answering questions at [GitHub Discussions](https://github.com/vitejs/vite/discussions) and helping others in the community in [Vite Land](https://chat.vitejs.dev).
+
+## Acknowledgments
+
+Vite 5.1 is possible thanks to our community of contributors, maintainers in the ecosystem, and the [Vite Team](/team). A shout out to the individuals and companies sponsoring Vite development. [StackBlitz](https://stackblitz.com/), [Nuxt Labs](https://nuxtlabs.com/), and [Astro](https://astro.build) for hiring Vite team members. And also to the sponsors on [Vite's GitHub Sponsors](https://github.com/sponsors/vitejs), [Vite's Open Collective](https://opencollective.com/vite), and [Evan You's GitHub Sponsors](https://github.com/sponsors/yyx990803).
diff --git a/docs/blog/announcing-vite5.md b/docs/blog/announcing-vite5.md
new file mode 100644
index 00000000000000..dd4c1d46a275b0
--- /dev/null
+++ b/docs/blog/announcing-vite5.md
@@ -0,0 +1,110 @@
+---
+title: Vite 5.0 is out!
+author:
+ name: The Vite Team
+date: 2023-11-16
+sidebar: false
+head:
+ - - meta
+ - property: og:type
+ content: website
+ - - meta
+ - property: og:title
+ content: Announcing Vite 5
+ - - meta
+ - property: og:image
+ content: https://vitejs.dev/og-image-announcing-vite5.png
+ - - meta
+ - property: og:url
+ content: https://vitejs.dev/blog/announcing-vite5
+ - - meta
+ - property: og:description
+ content: Vite 5 Release Announcement
+ - - meta
+ - name: twitter:card
+ content: summary_large_image
+---
+
+# Vite 5.0 is out!
+
+_November 16, 2023_
+
+![Vite 5 Announcement Cover Image](/og-image-announcing-vite5.png)
+
+Vite 4 [was released](./announcing-vite4.md) almost a year ago, and it served as a solid base for the ecosystem. npm downloads per week jumped from 2.5 million to 7.5 million, as projects keep building on a shared infrastructure. Frameworks continued to innovate, and on top of [Astro](https://astro.build/), [Nuxt](https://nuxt.com/), [SvelteKit](https://kit.svelte.dev/), [Solid Start](https://www.solidjs.com/blog/introducing-solidstart), [Qwik City](https://qwik.builder.io/qwikcity/overview/), between others, we saw new frameworks joining and making the ecosystem stronger. [RedwoodJS](https://redwoodjs.com/) and [Remix](https://remix.run/) switching to Vite paves the way for further adoption in the React ecosystem. [Vitest](https://vitest.dev) kept growing at an even faster pace than Vite. Its team has been hard at work and will soon [release Vitest 1.0](https://github.com/vitest-dev/vitest/issues/3596). The story of Vite when used with other tools such as [Storybook](https://storybook.js.org), [Nx](https://nx.dev), and [Playwright](https://playwright.dev) kept improving, and the same goes for environments, with Vite dev working both in [Deno](https://deno.com) and [Bun](https://bun.sh).
+
+We had the second edition of [ViteConf](https://viteconf.org/23/replay) a month ago, hosted by [StackBlitz](https://stackblitz.com). Like last year, most of the projects in the ecosystem got together to share ideas and connect to keep expanding the commons. We're also seeing new pieces complement the meta-framework tool belt like [Volar](https://volarjs.dev/) and [Nitro](https://nitro.unjs.io/). The Rollup team released [Rollup 4](https://rollupjs.org) that same day, a tradition Lukas started last year.
+
+Six months ago, Vite 4.3 [was released](./announcing-vite4.md). This release significantly improved the dev server performance. However, there is still ample room for improvement. At ViteConf, [Evan You unveiled Vite's long-term plan to work on Rolldown](https://www.youtube.com/watch?v=hrdwQHoAp0M), a Rust-port of Rollup with compatible APIs. Once it is ready, we intend to use it in Vite Core to take on the tasks of both Rollup and esbuild. This will mean a boost in build performance (and later on in dev performance too as we move perf-sensitive parts of Vite itself to Rust), and a big reduction of inconsistencies between dev and build. Rolldown is currently in early stages and the team is preparing to open source the codebase before the end of the year. Stay tuned!
+
+Today, we mark another big milestone in Vite's path. The Vite [team](/team), [contributors](https://github.com/vitejs/vite/graphs/contributors), and ecosystem partners, are excited to announce the release of Vite 5. Vite is now using [Rollup 4](https://github.com/vitejs/vite/pull/14508), which already represents a big boost in build performance. And there are also new options to improve your dev server performance profile.
+
+Vite 5 focuses on cleaning up the API (removing deprecated features) and streamlines several features closing long-standing issues, for example switching `define` to use proper AST replacements instead of regexes. We also continue to take steps to future-proof Vite (Node.js 18+ is now required, and [the CJS Node API has been deprecated](/guide/migration#deprecate-cjs-node-api)).
+
+Quick links:
+
+- [Docs](/)
+- [Migration Guide](/guide/migration)
+- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#500-2023-11-16)
+
+Docs in other languages:
+
+- [简体中文](https://cn.vitejs.dev/)
+- [日本語](https://ja.vitejs.dev/)
+- [Español](https://es.vitejs.dev/)
+- [Português](https://pt.vitejs.dev/)
+- [한국어](https://ko.vitejs.dev/)
+- [Deutsch](https://de.vitejs.dev/) (new translation!)
+
+If you're new to Vite, we suggest reading first the [Getting Started](/guide/) and [Features](/guide/features) guides.
+
+We appreciate the more than [850 contributors to Vite Core](https://github.com/vitejs/vite/graphs/contributors), and the maintainers and contributors of Vite plugins, integrations, tools, and translations that have helped us reach here. We encourage you to get involved and continue to improve Vite with us. You can learn more at our [Contributing Guide](https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md). To get started, we recommend [triaging issues](https://github.com/vitejs/vite/issues), [reviewing PRs](https://github.com/vitejs/vite/pulls), sending failing tests PRs based on open issues, and helping others in [Discussions](https://github.com/vitejs/vite/discussions) and Vite Land's [help forum](https://discord.com/channels/804011606160703521/1019670660856942652). You'll learn a lot along the way and have a smooth path to further contributions to the project. If you have doubts, join us on our [Discord community](http://chat.vitejs.dev/) and say hi on the [#contributing channel](https://discord.com/channels/804011606160703521/804439875226173480).
+
+To stay up to date, follow us on [X](https://twitter.com/vite_js) or [Mastodon](https://webtoo.ls/@vite).
+
+## Quick start with Vite 5
+
+Use `pnpm create vite` to scaffold a Vite project with your preferred framework, or open a started template online to play with Vite 5 using [vite.new](https://vite.new). You can also run `pnpm create vite-extra` to get access to templates from other frameworks and runtimes (Solid, Deno, SSR, and library starters). `create vite-extra` templates are also available when you run `create vite` under the `Others` option.
+
+Note that Vite starter templates are intended to be used as a playground to test Vite with different frameworks. When building your next project, we recommend reaching out to the starters recommended by each framework. Some frameworks now redirect in `create vite` to their starters too (`create-vue` and `Nuxt 3` for Vue, and `SvelteKit` for Svelte).
+
+## Node.js Support
+
+Vite no longer supports Node.js 14 / 16 / 17 / 19, which reached its EOL. Node.js 18 / 20+ is now required.
+
+## Performance
+
+On top of Rollup 4's build performance improvements, there is a new guide to help you identify and fix common performance issues at [https://vitejs.dev/guide/performance](/guide/performance).
+
+Vite 5 also introduces [server.warmup](/guide/performance.html#warm-up-frequently-used-files), a new feature to improve startup time. It lets you define a list of modules that should be pre-transformed as soon as the server starts. When using [`--open` or `server.open`](/config/server-options.html#server-open), Vite will also automatically warm up the entry point of your app or the provided URL to open.
+
+## Main Changes
+
+- [Vite is now powered by Rollup 4](/guide/migration#rollup-4)
+- [The CJS Node API has been deprecated](/guide/migration#deprecate-cjs-node-api)
+- [Rework `define` and `import.meta.env.*` replacement strategy](/guide/migration#rework-define-and-import-meta-env-replacement-strategy)
+- [SSR externalized modules value now matches production](/guide/migration#ssr-externalized-modules-value-now-matches-production)
+- [`worker.plugins` is now a function](/guide/migration#worker-plugins-is-now-a-function)
+- [Allow path containing `.` to fallback to index.html](/guide/migration#allow-path-containing-to-fallback-to-index-html)
+- [Align dev and preview HTML serving behavior](/guide/migration#align-dev-and-preview-html-serving-behaviour)
+- [Manifest files are now generated in `.vite` directory by default](/guide/migration#manifest-files-are-now-generated-in-vite-directory-by-default)
+- [CLI shortcuts require an additional `Enter` press](/guide/migration#cli-shortcuts-require-an-additional-enter-press)
+- [Update `experimentalDecorators` and `useDefineForClassFields` TypeScript behavior](/guide/migration#update-experimentaldecorators-and-usedefineforclassfields-typescript-behaviour)
+- [Remove `--https` flag and `https: true`](/guide/migration#remove-https-flag-and-https-true)
+- [Remove `resolvePackageEntry` and `resolvePackageData` APIs](/guide/migration#remove-resolvepackageentry-and-resolvepackagedata-apis)
+- [Removes previously deprecated APIs](/guide/migration#removed-deprecated-apis)
+- [Read more about advanced changes affecting plugin and tool authors](/guide/migration#advanced)
+
+## Migrating to Vite 5
+
+We have worked with ecosystem partners to ensure a smooth migration to this new major. Once again, [vite-ecosystem-ci](https://www.youtube.com/watch?v=7L4I4lDzO48) has been crucial to help us make bolder changes while avoiding regressions. We're thrilled to see other ecosystems adopt similar schemes to improve the collaboration between their projects and downstream maintainers.
+
+For most projects, the update to Vite 5 should be straight forward. But we advise reviewing the [detailed Migration Guide](/guide/migration) before upgrading.
+
+A low level breakdown with the full list of changes to Vite core can be found at the [Vite 5 Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#500-2023-11-16).
+
+## Acknowledgments
+
+Vite 5 is the result of long hours of work by our community of contributors, downstream maintainers, plugins authors, and the [Vite Team](/team). A big shout out to [Bjorn Lu](https://twitter.com/bluwyoo) for leading the release process for this major.
+
+We're also thankful to individuals and companies sponsoring Vite development. [StackBlitz](https://stackblitz.com/), [Nuxt Labs](https://nuxtlabs.com/), and [Astro](https://astro.build) continue to invest in Vite by hiring Vite team members. A shout out to sponsors on [Vite's GitHub Sponsors](https://github.com/sponsors/vitejs), [Vite's Open Collective](https://opencollective.com/vite), and [Evan You's GitHub Sponsors](https://github.com/sponsors/yyx990803). A special mention to [Remix](https://remix.run/) for becoming a Gold sponsor and contributing back after switching to Vite.
diff --git a/docs/config/build-options.md b/docs/config/build-options.md
index 757847c41e3d74..3713daf534b349 100644
--- a/docs/config/build-options.md
+++ b/docs/config/build-options.md
@@ -48,11 +48,19 @@ type ResolveModulePreloadDependenciesFn = (
The `resolveDependencies` function will be called for each dynamic import with a list of the chunks it depends on, and it will also be called for each chunk imported in entry HTML files. A new dependencies array can be returned with these filtered or more dependencies injected, and their paths modified. The `deps` paths are relative to the `build.outDir`. Returning a relative path to the `hostId` for `hostType === 'js'` is allowed, in which case `new URL(dep, import.meta.url)` is used to get an absolute path when injecting this module preload in the HTML head.
-```js
+```js twoslash
+/** @type {import('vite').UserConfig} */
+const config = {
+ // prettier-ignore
+ build: {
+// ---cut-before---
modulePreload: {
resolveDependencies: (filename, deps, { hostId, hostType }) => {
return deps.filter(condition)
- }
+ },
+},
+// ---cut-after---
+ },
}
```
@@ -82,11 +90,13 @@ Specify the directory to nest generated assets under (relative to `build.outDir`
## build.assetsInlineLimit
-- **Type:** `number`
+- **Type:** `number` | `((filePath: string, content: Buffer) => boolean | undefined)`
- **Default:** `4096` (4 KiB)
Imported or referenced assets that are smaller than this threshold will be inlined as base64 URLs to avoid extra http requests. Set to `0` to disable inlining altogether.
+If a callback is passed, a boolean can be returned to opt-in or opt-out. If nothing is returned the default logic applies.
+
Git LFS placeholders are automatically excluded from inlining because they do not contain the content of the file they represent.
::: tip Note
@@ -191,7 +201,7 @@ During the SSR build, static assets aren't emitted as it is assumed they would b
## build.minify
- **Type:** `boolean | 'terser' | 'esbuild'`
-- **Default:** `'esbuild'`
+- **Default:** `'esbuild'` for client build, `false` for SSR build
Set to `false` to disable minification, or specify the minifier to use. The default is [esbuild](https://github.com/evanw/esbuild) which is 20 ~ 40x faster than terser and only 1 ~ 2% worse compression. [Benchmarks](https://github.com/privatenumber/minification-benchmarks)
diff --git a/docs/config/dep-optimization-options.md b/docs/config/dep-optimization-options.md
index ec499f4d9ccf16..43152b738e483d 100644
--- a/docs/config/dep-optimization-options.md
+++ b/docs/config/dep-optimization-options.md
@@ -8,7 +8,7 @@
By default, Vite will crawl all your `.html` files to detect dependencies that need to be pre-bundled (ignoring `node_modules`, `build.outDir`, `__tests__` and `coverage`). If `build.rollupOptions.input` is specified, Vite will crawl those entry points instead.
-If neither of these fit your needs, you can specify custom entries using this option - the value should be a [fast-glob pattern](https://github.com/mrmlnc/fast-glob#basic-syntax) or array of patterns that are relative from Vite project root. This will overwrite default entries inference. Only `node_modules` and `build.outDir` folders will be ignored by default when `optimizeDeps.entries` is explicitly defined. If other folders need to be ignored, you can use an ignore pattern as part of the entries list, marked with an initial `!`.
+If neither of these fit your needs, you can specify custom entries using this option - the value should be a [fast-glob pattern](https://github.com/mrmlnc/fast-glob#basic-syntax) or array of patterns that are relative from Vite project root. This will overwrite default entries inference. Only `node_modules` and `build.outDir` folders will be ignored by default when `optimizeDeps.entries` is explicitly defined. If other folders need to be ignored, you can use an ignore pattern as part of the entries list, marked with an initial `!`. If you don't want to ignore `node_modules` and `build.outDir`, you can specify using literal string paths (without fast-glob patterns) instead.
## optimizeDeps.exclude
@@ -19,7 +19,9 @@ Dependencies to exclude from pre-bundling.
:::warning CommonJS
CommonJS dependencies should not be excluded from optimization. If an ESM dependency is excluded from optimization, but has a nested CommonJS dependency, the CommonJS dependency should be added to `optimizeDeps.include`. Example:
-```js
+```js twoslash
+import { defineConfig } from 'vite'
+// ---cut---
export default defineConfig({
optimizeDeps: {
include: ['esm-dep > cjs-dep'],
@@ -35,9 +37,11 @@ export default defineConfig({
By default, linked packages not inside `node_modules` are not pre-bundled. Use this option to force a linked package to be pre-bundled.
-**Experimental:** If you're using a library with many deep imports, you can also specify a trailing glob pattern to pre-bundle all deep imports at once. This will avoid constantly pre-bundling whenever a new deep import is used. For example:
+**Experimental:** If you're using a library with many deep imports, you can also specify a trailing glob pattern to pre-bundle all deep imports at once. This will avoid constantly pre-bundling whenever a new deep import is used. [Give Feedback](https://github.com/vitejs/vite/discussions/15833). For example:
-```js
+```js twoslash
+import { defineConfig } from 'vite'
+// ---cut---
export default defineConfig({
optimizeDeps: {
include: ['my-lib/components/**/*.vue'],
@@ -47,7 +51,17 @@ export default defineConfig({
## optimizeDeps.esbuildOptions
-- **Type:** [`EsbuildBuildOptions`](https://esbuild.github.io/api/#simple-options)
+- **Type:** [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)`<`[`EsbuildBuildOptions`](https://esbuild.github.io/api/#simple-options)`,
+| 'bundle'
+| 'entryPoints'
+| 'external'
+| 'write'
+| 'watch'
+| 'outdir'
+| 'outfile'
+| 'outbase'
+| 'outExtension'
+| 'metafile'>`
Options to pass to esbuild during the dep scanning and optimization.
@@ -62,18 +76,27 @@ Certain options are omitted since changing them would not be compatible with Vit
Set to `true` to force dependency pre-bundling, ignoring previously cached optimized dependencies.
+## optimizeDeps.holdUntilCrawlEnd
+
+- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/15834)
+- **Type:** `boolean`
+- **Default:** `true`
+
+When enabled, it will hold the first optimized deps results until all static imports are crawled on cold start. This avoids the need for full-page reloads when new dependencies are discovered and they trigger the generation of new common chunks. If all dependencies are found by the scanner plus the explicitly defined ones in `include`, it is better to disable this option to let the browser process more requests in parallel.
+
## optimizeDeps.disabled
+- **Deprecated**
- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/13839)
- **Type:** `boolean | 'build' | 'dev'`
- **Default:** `'build'`
-Disables dependencies optimizations, `true` disables the optimizer during build and dev. Pass `'build'` or `'dev'` to only disable the optimizer in one of the modes. Dependency optimization is enabled by default in dev only.
+This option is deprecated. As of Vite 5.1, pre-bundling of dependencies during build have been removed. Setting `optimizeDeps.disabled` to `true` or `'dev'` disables the optimizer, and configured to `false` or `'build'` leaves the optimizer during dev enabled.
-:::warning
-Optimizing dependencies in build mode is **experimental**. If enabled, it removes one of the most significant differences between dev and prod. [`@rollup/plugin-commonjs`](https://github.com/rollup/plugins/tree/master/packages/commonjs) is no longer needed in this case since esbuild converts CJS-only dependencies to ESM.
+To disable the optimizer completely, use `optimizeDeps.noDiscovery: true` to disallow automatic discovery of dependencies and leave `optimizeDeps.include` undefined or empty.
-If you want to try this build strategy, you can use `optimizeDeps.disabled: false`. `@rollup/plugin-commonjs` can be removed by passing `build.commonjsOptions: { include: [] }`.
+:::warning
+Optimizing dependencies during build time was an **experimental** feature. Projects trying out this strategy also removed `@rollup/plugin-commonjs` using `build.commonjsOptions: { include: [] }`. If you did so, a warning will guide you to re-enable it to support CJS only packages while bundling.
:::
## optimizeDeps.needsInterop
diff --git a/docs/config/index.md b/docs/config/index.md
index 6932c7f29dc595..e599295b3bd80b 100644
--- a/docs/config/index.md
+++ b/docs/config/index.md
@@ -50,7 +50,9 @@ Vite also directly supports TS config files. You can use `vite.config.ts` with t
If the config needs to conditionally determine options based on the command (`serve` or `build`), the [mode](/guide/env-and-mode) being used, if it's an SSR build (`isSsrBuild`), or is previewing the build (`isPreview`), it can export a function instead:
-```js
+```js twoslash
+import { defineConfig } from 'vite'
+// ---cut---
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
@@ -65,7 +67,7 @@ export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
})
```
-It is important to note that in Vite's API the `command` value is `serve` during dev (in the cli `vite`, `vite dev`, and `vite serve` are aliases), and `build` when building for production (`vite build`).
+It is important to note that in Vite's API the `command` value is `serve` during dev (in the cli [`vite`](/guide/cli#vite), `vite dev`, and `vite serve` are aliases), and `build` when building for production ([`vite build`](/guide/cli#vite-build)).
`isSsrBuild` and `isPreview` are additional optional flags to differentiate the kind of `build` and `serve` commands respectively. Some tools that load the Vite config may not support these flags and will pass `undefined` instead. Hence, it's recommended to use explicit comparison against `true` and `false`.
@@ -73,7 +75,9 @@ It is important to note that in Vite's API the `command` value is `serve` during
If the config needs to call async functions, it can export an async function instead. And this async function can also be passed through `defineConfig` for improved intellisense support:
-```js
+```js twoslash
+import { defineConfig } from 'vite'
+// ---cut---
export default defineConfig(async ({ command, mode }) => {
const data = await asyncFunction()
return {
@@ -88,7 +92,7 @@ Environmental Variables can be obtained from `process.env` as usual.
Note that Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affect the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed.
-```js
+```js twoslash
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ command, mode }) => {
diff --git a/docs/config/preview-options.md b/docs/config/preview-options.md
index 7d7aca988cda87..6c4370142d5140 100644
--- a/docs/config/preview-options.md
+++ b/docs/config/preview-options.md
@@ -46,7 +46,7 @@ Set to `true` to exit if port is already in use, instead of automatically trying
## preview.https
-- **Type:** `boolean | https.ServerOptions`
+- **Type:** `https.ServerOptions`
- **Default:** [`server.https`](./server-options#server-https)
Enable TLS + HTTP/2. Note this downgrades to TLS only when the [`server.proxy` option](./server-options#server-proxy) is also used.
diff --git a/docs/config/server-options.md b/docs/config/server-options.md
index 9efdd443fea150..a9d5d52df3c826 100644
--- a/docs/config/server-options.md
+++ b/docs/config/server-options.md
@@ -18,10 +18,10 @@ The first case is when `localhost` is used. Node.js under v17 reorders the resul
You can set [`dns.setDefaultResultOrder('verbatim')`](https://nodejs.org/api/dns.html#dns_dns_setdefaultresultorder_order) to disable the reordering behavior. Vite will then print the address as `localhost`.
-```js
+```js twoslash
// vite.config.js
import { defineConfig } from 'vite'
-import dns from 'dns'
+import dns from 'node:dns'
dns.setDefaultResultOrder('verbatim')
@@ -90,7 +90,7 @@ Configure custom proxy rules for the dev server. Expects an object of `{ key: op
Note that if you are using non-relative [`base`](/config/shared-options.md#base), you must prefix each key with that `base`.
-Extends [`http-proxy`](https://github.com/http-party/node-http-proxy#options). Additional options are [here](https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/proxy.ts#L12).
+Extends [`http-proxy`](https://github.com/http-party/node-http-proxy#options). Additional options are [here](https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/proxy.ts#L13).
In some cases, you might also want to configure the underlying dev server (e.g. to add custom middlewares to the internal [connect](https://github.com/senchalabs/connect) app). In order to do that, you need to write your own [plugin](/guide/using-plugins.html) and use [configureServer](/guide/api-plugin.html#configureserver) function.
@@ -123,9 +123,11 @@ export default defineConfig({
},
},
// Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io
+ // Exercise caution using `rewriteWsOrigin` as it can leave the proxying open to CSRF attacks.
'/socket.io': {
target: 'ws://localhost:5174',
ws: true,
+ rewriteWsOrigin: true,
},
},
},
@@ -152,6 +154,8 @@ Disable or configure HMR connection (in cases where the HMR websocket must use a
Set `server.hmr.overlay` to `false` to disable the server error overlay.
+`protocol` sets the WebSocket protocol used for the HMR connection: `ws` (WebSocket) or `wss` (WebSocket Secure).
+
`clientPort` is an advanced option that overrides the port only on the client side, allowing you to serve the websocket on a different port than the client code looks for it on.
When `server.hmr.server` is defined, Vite will process the HMR connection requests through the provided server. If not in middleware mode, Vite will attempt to process HMR connection requests through the existing server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port.
@@ -202,7 +206,7 @@ export default defineConfig({
File system watcher options to pass on to [chokidar](https://github.com/paulmillr/chokidar#api).
-The Vite server watcher watches the `root` and skips the `.git/` and `node_modules/` directories by default. When updating a watched file, Vite will apply HMR and update the page only if needed.
+The Vite server watcher watches the `root` and skips the `.git/`, `node_modules/`, and Vite's `cacheDir` and `build.outDir` directories by default. When updating a watched file, Vite will apply HMR and update the page only if needed.
If set to `null`, no files will be watched. `server.watcher` will provide a compatible event emitter, but calling `add` or `unwatch` will have no effect.
@@ -236,7 +240,7 @@ Create Vite server in middleware mode.
- **Example:**
-```js
+```js twoslash
import express from 'express'
import { createServer as createViteServer } from 'vite'
@@ -356,9 +360,9 @@ export default defineConfig({
// in their paths to the ignore list.
sourcemapIgnoreList(sourcePath, sourcemapPath) {
return sourcePath.includes('node_modules')
- }
- }
-};
+ },
+ },
+})
```
::: tip Note
diff --git a/docs/config/shared-options.md b/docs/config/shared-options.md
index cbf0abe12acc6d..19eb96e0f74439 100644
--- a/docs/config/shared-options.md
+++ b/docs/config/shared-options.md
@@ -13,11 +13,12 @@ See [Project Root](/guide/#index-html-and-project-root) for more details.
- **Type:** `string`
- **Default:** `/`
+- **Related:** [`server.origin`](/config/server-options.md#server-origin)
Base public path when served in development or production. Valid values include:
- Absolute URL pathname, e.g. `/foo/`
-- Full URL, e.g. `https://foo.com/`
+- Full URL, e.g. `https://bar.com/foo/` (The origin part won't be used in development so the value is the same as `/foo/`)
- Empty string or `./` (for embedded deployment)
See [Public Base Path](/guide/build#public-base-path) for more details.
@@ -162,26 +163,43 @@ Enabling this setting causes vite to determine file identity by the original fil
- **Related:** [esbuild#preserve-symlinks](https://esbuild.github.io/api/#preserve-symlinks), [webpack#resolve.symlinks
](https://webpack.js.org/configuration/resolve/#resolvesymlinks)
+## html.cspNonce
+
+- **Type:** `string`
+- **Related:** [Content Security Policy (CSP)](/guide/features#content-security-policy-csp)
+
+A nonce value placeholder that will be used when generating script / style tags. Setting this value will also generate a meta tag with nonce value.
+
## css.modules
- **Type:**
```ts
interface CSSModulesOptions {
+ getJSON?: (
+ cssFileName: string,
+ json: Record,
+ outputFileName: string,
+ ) => void
scopeBehaviour?: 'global' | 'local'
globalModulePaths?: RegExp[]
+ exportGlobals?: boolean
generateScopedName?:
| string
| ((name: string, filename: string, css: string) => string)
hashPrefix?: string
/**
- * default: null
+ * default: undefined
*/
localsConvention?:
| 'camelCase'
| 'camelCaseOnly'
| 'dashes'
| 'dashesOnly'
- | null
+ | ((
+ originalClassName: string,
+ generatedClassName: string,
+ inputFile: string,
+ ) => string)
}
```
@@ -211,17 +229,12 @@ Specify options to pass to CSS pre-processors. The file extensions are used as k
- `less` - [Options](https://lesscss.org/usage/#less-options).
- `styl`/`stylus` - Only [`define`](https://stylus-lang.com/docs/js.html#define-name-node) is supported, which can be passed as an object.
-All preprocessor options also support the `additionalData` option, which can be used to inject extra code for each style content. Note that if you include actual styles and not just variables, those styles will be duplicated in the final bundle.
-
-Example:
+**Example:**
```js
export default defineConfig({
css: {
preprocessorOptions: {
- scss: {
- additionalData: `$injectedColor: orange;`,
- },
less: {
math: 'parens-division',
},
@@ -235,6 +248,34 @@ export default defineConfig({
})
```
+### css.preprocessorOptions[extension].additionalData
+
+- **Type:** `string | ((source: string, filename: string) => (string | { content: string; map?: SourceMap }))`
+
+This option can be used to inject extra code for each style content. Note that if you include actual styles and not just variables, those styles will be duplicated in the final bundle.
+
+**Example:**
+
+```js
+export default defineConfig({
+ css: {
+ preprocessorOptions: {
+ scss: {
+ additionalData: `$injectedColor: orange;`,
+ },
+ },
+ },
+})
+```
+
+## css.preprocessorMaxWorkers
+
+- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/15835)
+- **Type:** `number | true`
+- **Default:** `0` (does not create any workers and run in the main thread)
+
+If this option is set, CSS preprocessors will run in workers when possible. `true` means the number of CPUs minus 1.
+
## css.devSourcemap
- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/13845)
@@ -251,6 +292,10 @@ Whether to enable sourcemaps during dev.
Selects the engine used for CSS processing. Check out [Lightning CSS](../guide/features.md#lightning-css) for more information.
+::: info Duplicate `@import`s
+Note that postcss (postcss-import) has a different behavior with duplicated `@import` from browsers. See [postcss/postcss-import#462](https://github.com/postcss/postcss-import/issues/462).
+:::
+
## css.lightningcss
- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/13835)
@@ -374,7 +419,7 @@ Adjust console output verbosity. Default is `'info'`.
Use a custom logger to log messages. You can use Vite's `createLogger` API to get the default logger and customize it to, for example, change the message or filter out certain warnings.
-```js
+```ts twoslash
import { createLogger, defineConfig } from 'vite'
const logger = createLogger()
diff --git a/docs/config/ssr-options.md b/docs/config/ssr-options.md
index d5f96bdb415fca..d925490e53dcb2 100644
--- a/docs/config/ssr-options.md
+++ b/docs/config/ssr-options.md
@@ -2,17 +2,25 @@
## ssr.external
-- **Type:** `string[]`
+- **Type:** `string[] | true`
- **Related:** [SSR Externals](/guide/ssr#ssr-externals)
-Force externalize dependencies for SSR.
+Externalize the given dependencies and their transitive dependencies for SSR. By default, all dependencies are externalized except for linked dependencies (for HMR). If you prefer to externalize the linked dependency, you can pass its name to this option.
+
+If `true`, all dependencies including linked dependencies are externalized.
+
+Note that the explicitly listed dependencies (using `string[]` type) will always take priority if they're also listed in `ssr.noExternal` (using any type).
## ssr.noExternal
- **Type:** `string | RegExp | (string | RegExp)[] | true`
- **Related:** [SSR Externals](/guide/ssr#ssr-externals)
-Prevent listed dependencies from being externalized for SSR. If `true`, no dependencies are externalized.
+Prevent listed dependencies from being externalized for SSR, which they will get bundled in build. By default, only linked dependencies are not externalized (for HMR). If you prefer to externalize the linked dependency, you can pass its name to the `ssr.external` option.
+
+If `true`, no dependencies are externalized. However, dependencies explicitly listed in `ssr.external` (using `string[]` type) can take priority and still be externalized. If `ssr.target: 'node'` is set, Node.js built-ins will also be externalized by default.
+
+Note that if both `ssr.noExternal: true` and `ssr.external: true` are configured, `ssr.noExternal` takes priority and no dependencies are externalized.
## ssr.target
@@ -26,7 +34,7 @@ Build target for the SSR server.
- **Type:** `string[]`
- **Related:** [Resolve Conditions](./shared-options.md#resolve-conditions)
-Defaults to the the root [`resolve.conditions`](./shared-options.md#resolve-conditions).
+Defaults to the root [`resolve.conditions`](./shared-options.md#resolve-conditions).
These conditions are used in the plugin pipeline, and only affect non-externalized dependencies during the SSR build. Use `ssr.resolve.externalConditions` to affect externalized imports.
diff --git a/docs/guide/api-hmr.md b/docs/guide/api-hmr.md
index e55f0af47090e0..e9a44eb0aaca88 100644
--- a/docs/guide/api-hmr.md
+++ b/docs/guide/api-hmr.md
@@ -8,15 +8,15 @@ The manual HMR API is primarily intended for framework and tooling authors. As a
Vite exposes its manual HMR API via the special `import.meta.hot` object:
-```ts
+```ts twoslash
+import type { ModuleNamespace } from 'vite/types/hot.d.ts'
+import type { InferCustomEventPayload } from 'vite/types/customEvent.d.ts'
+
+// ---cut---
interface ImportMeta {
readonly hot?: ViteHotContext
}
-type ModuleNamespace = Record & {
- [Symbol.toStringTag]: 'Module'
-}
-
interface ViteHotContext {
readonly data: any
@@ -32,7 +32,6 @@ interface ViteHotContext {
prune(cb: (data: any) => void): void
invalidate(message?: string): void
- // `InferCustomEventPayload` provides types for built-in Vite events
on(
event: T,
cb: (payload: InferCustomEventPayload) => void,
@@ -67,7 +66,9 @@ Vite provides type definitions for `import.meta.hot` in [`vite/client.d.ts`](htt
For a module to self-accept, use `import.meta.hot.accept` with a callback which receives the updated module:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
export const count = 1
if (import.meta.hot) {
@@ -90,7 +91,13 @@ Vite requires that the call to this function appears as `import.meta.hot.accept(
A module can also accept updates from direct dependencies without reloading itself:
-```js
+```js twoslash
+// @filename: /foo.d.ts
+export declare const foo: () => void
+
+// @filename: /example.js
+import 'vite/client'
+// ---cut---
import { foo } from './foo.js'
foo()
@@ -117,7 +124,9 @@ if (import.meta.hot) {
A self-accepting module or a module that expects to be accepted by others can use `hot.dispose` to clean-up any persistent side effects created by its updated copy:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
function setupSideEffect() {}
setupSideEffect()
@@ -133,7 +142,9 @@ if (import.meta.hot) {
Register a callback that will call when the module is no longer imported on the page. Compared to `hot.dispose`, this can be used if the source code cleans up side-effects by itself on updates and you only need to clean-up when it's removed from the page. Vite currently uses this for `.css` imports.
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
function setupOrReuseSideEffect() {}
setupOrReuseSideEffect()
@@ -151,7 +162,9 @@ The `import.meta.hot.data` object is persisted across different instances of the
Note that re-assignment of `data` itself is not supported. Instead, you should mutate properties of the `data` object so information added from other handlers are preserved.
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// ok
import.meta.hot.data.someValue = 'hello'
@@ -169,7 +182,9 @@ A self-accepting module may realize during runtime that it can't handle a HMR up
Note that you should always call `import.meta.hot.accept` even if you plan to call `invalidate` immediately afterwards, or else the HMR client won't listen for future changes to the self-accepting module. To communicate your intent clearly, we recommend calling `invalidate` within the `accept` callback like so:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import.meta.hot.accept((module) => {
// You may use the new module instance to decide whether to invalidate.
if (cannotHandleUpdate(module)) {
@@ -197,7 +212,7 @@ Custom HMR events can also be sent from plugins. See [handleHotUpdate](./api-plu
## `hot.off(event, cb)`
-Remove callback from the event listeners
+Remove callback from the event listeners.
## `hot.send(event, data)`
@@ -205,4 +220,10 @@ Send custom events back to Vite's dev server.
If called before connected, the data will be buffered and sent once the connection is established.
-See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details.
+See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details, including a section on [Typing Custom Events](/guide/api-plugin.html#typescript-for-custom-events).
+
+## Further Reading
+
+If you'd like to learn more about how to use the HMR API and how it works under-the-hood. Check out these resources:
+
+- [Hot Module Replacement is Easy](https://bjornlu.com/blog/hot-module-replacement-is-easy)
diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md
index 1ff419058f2706..573c8c32a394c6 100644
--- a/docs/guide/api-javascript.md
+++ b/docs/guide/api-javascript.md
@@ -12,32 +12,66 @@ async function createServer(inlineConfig?: InlineConfig): Promise
**Example Usage:**
-```js
-import { fileURLToPath } from 'url'
+```ts twoslash
+import { fileURLToPath } from 'node:url'
import { createServer } from 'vite'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
-;(async () => {
- const server = await createServer({
- // any valid user config options, plus `mode` and `configFile`
- configFile: false,
- root: __dirname,
- server: {
- port: 1337,
- },
- })
- await server.listen()
-
- server.printUrls()
- server.bindCLIShortcuts({ print: true })
-})()
+const server = await createServer({
+ // any valid user config options, plus `mode` and `configFile`
+ configFile: false,
+ root: __dirname,
+ server: {
+ port: 1337,
+ },
+})
+await server.listen()
+
+server.printUrls()
+server.bindCLIShortcuts({ print: true })
```
::: tip NOTE
When using `createServer` and `build` in the same Node.js process, both functions rely on `process.env.NODE_ENV` to work properly, which also depends on the `mode` config option. To prevent conflicting behavior, set `process.env.NODE_ENV` or the `mode` of the two APIs to `development`. Otherwise, you can spawn a child process to run the APIs separately.
:::
+::: tip NOTE
+When using [middleware mode](/config/server-options.html#server-middlewaremode) combined with [proxy config for WebSocket](/config/server-options.html#server-proxy), the parent http server should be provided in `middlewareMode` to bind the proxy correctly.
+
+
+Example
+
+```ts twoslash
+import http from 'http'
+import { createServer } from 'vite'
+
+const parentServer = http.createServer() // or express, koa, etc.
+
+const vite = await createServer({
+ server: {
+ // Enable middleware mode
+ middlewareMode: {
+ // Provide the parent http server for proxy WebSocket
+ server: parentServer,
+ },
+ proxy: {
+ '/ws': {
+ target: 'ws://localhost:3000',
+ // Proxying WebSocket
+ ws: true,
+ },
+ },
+ },
+})
+
+// @noErrors: 2339
+parentServer.use(vite.middlewares)
+```
+
+
+:::
+
## `InlineConfig`
The `InlineConfig` interface extends `UserConfig` with additional properties:
@@ -109,7 +143,11 @@ interface ViteDevServer {
/**
* Apply Vite built-in HTML transforms and any plugin HTML transforms.
*/
- transformIndexHtml(url: string, html: string): Promise
+ transformIndexHtml(
+ url: string,
+ html: string,
+ originalUrl?: string,
+ ): Promise
/**
* Load a given URL as an instantiated module for SSR.
*/
@@ -144,9 +182,21 @@ interface ViteDevServer {
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions): void
+ /**
+ * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
+ * are processed. If called from a load or transform plugin hook, the id needs to be
+ * passed as a parameter to avoid deadlocks. Calling this function after the first
+ * static imports section of the module graph has been processed will resolve immediately.
+ * @experimental
+ */
+ waitForRequestsIdle: (ignoredId?: string) => Promise
}
```
+:::info
+`waitForRequestsIdle` is meant to be used as a escape hatch to improve DX for features that can't be implemented following the on-demand nature of the Vite dev server. It can be used during startup by tools like Tailwind to delay generating the app CSS classes until the app code has been seen, avoiding flashes of style changes. When this function is used in a load or transform hook, and the default HTTP1 server is used, one of the six http channels will be blocked until the server processes all static imports. Vite's dependency optimizer currently uses this function to avoid full-page reloads on missing dependencies by delaying loading of pre-bundled dependencies until all imported dependencies have been collected from static imported sources. Vite may switch to a different strategy in a future major release, setting `optimizeDeps.crawlUntilStaticImports: false` by default to avoid the performance hit in large applications during cold start.
+:::
+
## `build`
**Type Signature:**
@@ -159,24 +209,22 @@ async function build(
**Example Usage:**
-```js
-import path from 'path'
-import { fileURLToPath } from 'url'
+```ts twoslash
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
import { build } from 'vite'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
-;(async () => {
- await build({
- root: path.resolve(__dirname, './project'),
- base: '/foo/',
- build: {
- rollupOptions: {
- // ...
- },
+await build({
+ root: path.resolve(__dirname, './project'),
+ base: '/foo/',
+ build: {
+ rollupOptions: {
+ // ...
},
- })
-})()
+ },
+})
```
## `preview`
@@ -189,20 +237,19 @@ async function preview(inlineConfig?: InlineConfig): Promise
**Example Usage:**
-```js
+```ts twoslash
import { preview } from 'vite'
-;(async () => {
- const previewServer = await preview({
- // any valid user config options, plus `mode` and `configFile`
- preview: {
- port: 8080,
- open: true,
- },
- })
- previewServer.printUrls()
- previewServer.bindCLIShortcuts({ print: true })
-})()
+const previewServer = await preview({
+ // any valid user config options, plus `mode` and `configFile`
+ preview: {
+ port: 8080,
+ open: true,
+ },
+})
+
+previewServer.printUrls()
+previewServer.bindCLIShortcuts({ print: true })
```
## `PreviewServer`
@@ -277,7 +324,17 @@ Deeply merge two Vite configs. `isRoot` represents the level within the Vite con
You can use the `defineConfig` helper to merge a config in callback form with another config:
-```ts
+```ts twoslash
+import {
+ defineConfig,
+ mergeConfig,
+ type UserConfigFnObject,
+ type UserConfig,
+} from 'vite'
+declare const configAsCallback: UserConfigFnObject
+declare const configAsObject: UserConfig
+
+// ---cut---
export default defineConfig((configEnv) =>
mergeConfig(configAsCallback(configEnv), configAsObject),
)
@@ -358,6 +415,7 @@ async function loadConfigFromFile(
configFile?: string,
configRoot: string = process.cwd(),
logLevel?: LogLevel,
+ customLogger?: Logger,
): Promise<{
path: string
config: UserConfig
@@ -366,3 +424,30 @@ async function loadConfigFromFile(
```
Load a Vite config file manually with esbuild.
+
+## `preprocessCSS`
+
+- **Experimental:** [Give Feedback](https://github.com/vitejs/vite/discussions/13815)
+
+**Type Signature:**
+
+```ts
+async function preprocessCSS(
+ code: string,
+ filename: string,
+ config: ResolvedConfig,
+): Promise
+
+interface PreprocessCSSResult {
+ code: string
+ map?: SourceMapInput
+ modules?: Record
+ deps?: Set
+}
+```
+
+Pre-processes `.css`, `.scss`, `.sass`, `.less`, `.styl` and `.stylus` files to plain CSS so it can be used in browsers or parsed by other tools. Similar to the [built-in CSS pre-processing support](/guide/features#css-pre-processors), the corresponding pre-processor must be installed if used.
+
+The pre-processor used is inferred from the `filename` extension. If the `filename` ends with `.module.{ext}`, it is inferred as a [CSS module](https://github.com/css-modules/css-modules) and the returned result will include a `modules` object mapping the original class names to the transformed ones.
+
+Note that pre-processing will not resolve URLs in `url()` or `image-set()`.
diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md
index d2f3b6ff8e25c9..852a6e408cfb37 100644
--- a/docs/guide/api-plugin.md
+++ b/docs/guide/api-plugin.md
@@ -402,6 +402,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
### `handleHotUpdate`
- **Type:** `(ctx: HmrContext) => Array | void | Promise | void>`
+- **See also:** [HMR API](./api-hmr)
Perform custom HMR update handling. The hook receives a context object with the following signature:
@@ -423,6 +424,25 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
- Filter and narrow down the affected module list so that the HMR is more accurate.
+ - Return an empty array and perform a full reload:
+
+ ```js
+ handleHotUpdate({ server, modules, timestamp }) {
+ server.ws.send({ type: 'full-reload' })
+ // Invalidate modules manually
+ const invalidatedModules = new Set()
+ for (const mod of modules) {
+ server.moduleGraph.invalidateModule(
+ mod,
+ invalidatedModules,
+ timestamp,
+ true
+ )
+ }
+ return []
+ }
+ ```
+
- Return an empty array and perform complete custom HMR handling by sending custom events to the client:
```js
@@ -458,6 +478,8 @@ A Vite plugin can additionally specify an `enforce` property (similar to webpack
- User plugins with `enforce: 'post'`
- Vite post build plugins (minify, manifest, reporting)
+Note that this is separate from hooks ordering, those are still separately subject to their `order` attribute [as usual for Rollup hooks](https://rollupjs.org/plugin-development/#build-hooks).
+
## Conditional Application
By default plugins are invoked for both serve and build. In cases where a plugin needs to be conditionally applied only during serve or build, use the `apply` property to only invoke them during `'build'` or `'serve'`:
@@ -509,8 +531,6 @@ export default defineConfig({
})
```
-Check out [Vite Rollup Plugins](https://vite-rollup-plugins.patak.dev) for a list of compatible official Rollup plugins with usage instructions.
-
## Path Normalization
Vite normalizes paths while resolving ids to use POSIX separators ( / ) while preserving the volume in Windows. On the other hand, Rollup keeps resolved paths untouched by default, so resolved ids have win32 separators ( \\ ) in Windows. However, Rollup plugins use a [`normalizePath` utility function](https://github.com/rollup/plugins/tree/master/packages/pluginutils#normalizepath) from `@rollup/pluginutils` internally, which converts separators to POSIX before performing comparisons. This means that when these plugins are used in Vite, the `include` and `exclude` config pattern and other similar paths against resolved ids comparisons work correctly.
@@ -534,7 +554,7 @@ Since Vite 2.9, we provide some utilities for plugins to help handle the communi
### Server to Client
-On the plugin side, we could use `server.ws.send` to broadcast events to all the clients:
+On the plugin side, we could use `server.ws.send` to broadcast events to the client:
```js
// vite.config.js
@@ -543,7 +563,6 @@ export default defineConfig({
{
// ...
configureServer(server) {
- // Example: wait for a client to connect before sending a message
server.ws.on('connection', () => {
server.ws.send('my:greetings', { msg: 'hello' })
})
@@ -559,7 +578,9 @@ We recommend **always prefixing** your event names to avoid collisions with othe
On the client side, use [`hot.on`](/guide/api-hmr.html#hot-on-event-cb) to listen to the events:
-```ts
+```ts twoslash
+import 'vite/client'
+// ---cut---
// client side
if (import.meta.hot) {
import.meta.hot.on('my:greetings', (data) => {
@@ -601,16 +622,40 @@ export default defineConfig({
### TypeScript for Custom Events
-It is possible to type custom events by extending the `CustomEventMap` interface:
+Internally, vite infers the type of a payload from the `CustomEventMap` interface, it is possible to type custom events by extending the interface:
+
+:::tip Note
+Make sure to include the `.d.ts` extension when specifying TypeScript declaration files. Otherwise, Typescript may not know which file the module is trying to extend.
+:::
```ts
// events.d.ts
-import 'vite/types/customEvent'
+import 'vite/types/customEvent.d.ts'
-declare module 'vite/types/customEvent' {
+declare module 'vite/types/customEvent.d.ts' {
interface CustomEventMap {
'custom:foo': { msg: string }
// 'event-key': payload
}
}
```
+
+This interface extension is utilized by `InferCustomEventPayload` to infer the payload type for event `T`. For more information on how this interface is utilized, refer to the [HMR API Documentation](./api-hmr#hmr-api).
+
+```ts twoslash
+import 'vite/client'
+import type { InferCustomEventPayload } from 'vite/types/customEvent.d.ts'
+declare module 'vite/types/customEvent.d.ts' {
+ interface CustomEventMap {
+ 'custom:foo': { msg: string }
+ }
+}
+// ---cut---
+type CustomFooPayload = InferCustomEventPayload<'custom:foo'>
+import.meta.hot?.on('custom:foo', (payload) => {
+ // The type of payload will be { msg: string }
+})
+import.meta.hot?.on('unknown:event', (payload) => {
+ // The type of payload will be any
+})
+```
diff --git a/docs/guide/api-vite-runtime.md b/docs/guide/api-vite-runtime.md
new file mode 100644
index 00000000000000..9aa579d268ddcf
--- /dev/null
+++ b/docs/guide/api-vite-runtime.md
@@ -0,0 +1,236 @@
+# Vite Runtime API
+
+:::warning Low-level API
+This API was introduced in Vite 5.1 as an experimental feature. It was added to [gather feedback](https://github.com/vitejs/vite/discussions/15774). There will likely be breaking changes, so make sure to pin the Vite version to `~5.1.0` when using it. This is a low-level API meant for library and framework authors. If your goal is to create an application, make sure to check out the higher-level SSR plugins and tools at [Awesome Vite SSR section](https://github.com/vitejs/awesome-vite#ssr) first.
+
+Currently, the API is being revised as the [Environment API](https://github.com/vitejs/vite/discussions/16358) which is released at `^6.0.0-alpha.0`.
+:::
+
+The "Vite Runtime" is a tool that allows running any code by processing it with Vite plugins first. It is different from `server.ssrLoadModule` because the runtime implementation is decoupled from the server. This allows library and framework authors to implement their own layer of communication between the server and the runtime.
+
+One of the goals of this feature is to provide a customizable API to process and run the code. Vite provides enough tools to use Vite Runtime out of the box, but users can build upon it if their needs do not align with Vite's built-in implementation.
+
+All APIs can be imported from `vite/runtime` unless stated otherwise.
+
+## `ViteRuntime`
+
+**Type Signature:**
+
+```ts
+export class ViteRuntime {
+ constructor(
+ public options: ViteRuntimeOptions,
+ public runner: ViteModuleRunner,
+ private debug?: ViteRuntimeDebugger,
+ ) {}
+ /**
+ * URL to execute. Accepts file path, server path, or id relative to the root.
+ */
+ public async executeUrl(url: string): Promise
+ /**
+ * Entry point URL to execute. Accepts file path, server path or id relative to the root.
+ * In the case of a full reload triggered by HMR, this is the module that will be reloaded.
+ * If this method is called multiple times, all entry points will be reloaded one at a time.
+ */
+ public async executeEntrypoint(url: string): Promise
+ /**
+ * Clear all caches including HMR listeners.
+ */
+ public clearCache(): void
+ /**
+ * Clears all caches, removes all HMR listeners, and resets source map support.
+ * This method doesn't stop the HMR connection.
+ */
+ public async destroy(): Promise
+ /**
+ * Returns `true` if the runtime has been destroyed by calling `destroy()` method.
+ */
+ public isDestroyed(): boolean
+}
+```
+
+::: tip Advanced Usage
+If you are just migrating from `server.ssrLoadModule` and want to support HMR, consider using [`createViteRuntime`](#createviteruntime) instead.
+:::
+
+The `ViteRuntime` class requires `root` and `fetchModule` options when initiated. Vite exposes `ssrFetchModule` on the [`server`](/guide/api-javascript) instance for easier integration with Vite SSR. Vite also exports `fetchModule` from its main entry point - it doesn't make any assumptions about how the code is running unlike `ssrFetchModule` that expects the code to run using `new Function`. This can be seen in source maps that these functions return.
+
+Runner in `ViteRuntime` is responsible for executing the code. Vite exports `ESModulesRunner` out of the box, it uses `new AsyncFunction` to run the code. You can provide your own implementation if your JavaScript runtime doesn't support unsafe evaluation.
+
+The two main methods that runtime exposes are `executeUrl` and `executeEntrypoint`. The only difference between them is that all modules executed by `executeEntrypoint` will be reexecuted if HMR triggers `full-reload` event. Be aware that Vite Runtime doesn't update `exports` object when this happens (it overrides it), you would need to run `executeUrl` or get the module from `moduleCache` again if you rely on having the latest `exports` object.
+
+**Example Usage:**
+
+```js
+import { ViteRuntime, ESModulesRunner } from 'vite/runtime'
+import { root, fetchModule } from './rpc-implementation.js'
+
+const runtime = new ViteRuntime(
+ {
+ root,
+ fetchModule,
+ // you can also provide hmr.connection to support HMR
+ },
+ new ESModulesRunner(),
+)
+
+await runtime.executeEntrypoint('/src/entry-point.js')
+```
+
+## `ViteRuntimeOptions`
+
+```ts
+export interface ViteRuntimeOptions {
+ /**
+ * Root of the project
+ */
+ root: string
+ /**
+ * A method to get the information about the module.
+ * For SSR, Vite exposes `server.ssrFetchModule` function that you can use here.
+ * For other runtime use cases, Vite also exposes `fetchModule` from its main entry point.
+ */
+ fetchModule: FetchFunction
+ /**
+ * Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
+ * Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
+ * You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
+ */
+ sourcemapInterceptor?:
+ | false
+ | 'node'
+ | 'prepareStackTrace'
+ | InterceptorOptions
+ /**
+ * Disable HMR or configure HMR options.
+ */
+ hmr?:
+ | false
+ | {
+ /**
+ * Configure how HMR communicates between the client and the server.
+ */
+ connection: HMRRuntimeConnection
+ /**
+ * Configure HMR logger.
+ */
+ logger?: false | HMRLogger
+ }
+ /**
+ * Custom module cache. If not provided, it creates a separate module cache for each ViteRuntime instance.
+ */
+ moduleCache?: ModuleCacheMap
+}
+```
+
+## `ViteModuleRunner`
+
+**Type Signature:**
+
+```ts
+export interface ViteModuleRunner {
+ /**
+ * Run code that was transformed by Vite.
+ * @param context Function context
+ * @param code Transformed code
+ * @param id ID that was used to fetch the module
+ */
+ runViteModule(
+ context: ViteRuntimeModuleContext,
+ code: string,
+ id: string,
+ ): Promise
+ /**
+ * Run externalized module.
+ * @param file File URL to the external module
+ */
+ runExternalModule(file: string): Promise
+}
+```
+
+Vite exports `ESModulesRunner` that implements this interface by default. It uses `new AsyncFunction` to run code, so if the code has inlined source map it should contain an [offset of 2 lines](https://tc39.es/ecma262/#sec-createdynamicfunction) to accommodate for new lines added. This is done automatically by `server.ssrFetchModule`. If your runner implementation doesn't have this constraint, you should use `fetchModule` (exported from `vite`) directly.
+
+## HMRRuntimeConnection
+
+**Type Signature:**
+
+```ts
+export interface HMRRuntimeConnection {
+ /**
+ * Checked before sending messages to the client.
+ */
+ isReady(): boolean
+ /**
+ * Send message to the client.
+ */
+ send(message: string): void
+ /**
+ * Configure how HMR is handled when this connection triggers an update.
+ * This method expects that connection will start listening for HMR updates and call this callback when it's received.
+ */
+ onUpdate(callback: (payload: HMRPayload) => void): void
+}
+```
+
+This interface defines how HMR communication is established. Vite exports `ServerHMRConnector` from the main entry point to support HMR during Vite SSR. The `isReady` and `send` methods are usually called when the custom event is triggered (like, `import.meta.hot.send("my-event")`).
+
+`onUpdate` is called only once when the new runtime is initiated. It passed down a method that should be called when connection triggers the HMR event. The implementation depends on the type of connection (as an example, it can be `WebSocket`/`EventEmitter`/`MessageChannel`), but it usually looks something like this:
+
+```js
+function onUpdate(callback) {
+ this.connection.on('hmr', (event) => callback(event.data))
+}
+```
+
+The callback is queued and it will wait for the current update to be resolved before processing the next update. Unlike the browser implementation, HMR updates in Vite Runtime wait until all listeners (like, `vite:beforeUpdate`/`vite:beforeFullReload`) are finished before updating the modules.
+
+## `createViteRuntime`
+
+**Type Signature:**
+
+```ts
+async function createViteRuntime(
+ server: ViteDevServer,
+ options?: MainThreadRuntimeOptions,
+): Promise
+```
+
+**Example Usage:**
+
+```js
+import { createServer } from 'vite'
+
+const __dirname = fileURLToPath(new URL('.', import.meta.url))
+
+;(async () => {
+ const server = await createServer({
+ root: __dirname,
+ })
+ await server.listen()
+
+ const runtime = await createViteRuntime(server)
+ await runtime.executeEntrypoint('/src/entry-point.js')
+})()
+```
+
+This method serves as an easy replacement for `server.ssrLoadModule`. Unlike `ssrLoadModule`, `createViteRuntime` provides HMR support out of the box. You can pass down [`options`](#mainthreadruntimeoptions) to customize how SSR runtime behaves to suit your needs.
+
+## `MainThreadRuntimeOptions`
+
+```ts
+export interface MainThreadRuntimeOptions
+ extends Omit {
+ /**
+ * Disable HMR or configure HMR logger.
+ */
+ hmr?:
+ | false
+ | {
+ logger?: false | HMRLogger
+ }
+ /**
+ * Provide a custom module runner. This controls how the code is executed.
+ */
+ runner?: ViteModuleRunner
+}
+```
diff --git a/docs/guide/assets.md b/docs/guide/assets.md
index dff926f2c2da31..4f81d04e496a80 100644
--- a/docs/guide/assets.md
+++ b/docs/guide/assets.md
@@ -7,7 +7,9 @@
Importing a static asset will return the resolved public URL when it is served:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
```
@@ -30,11 +32,25 @@ The behavior is similar to webpack's `file-loader`. The difference is that the i
- TypeScript, by default, does not recognize static asset imports as valid modules. To fix this, include [`vite/client`](./features#client-types).
+::: tip Inlining SVGs through `url()`
+When passing a URL of SVG to a manually constructed `url()` by JS, the variable should be wrapped within double quotes.
+
+```js twoslash
+import 'vite/client'
+// ---cut---
+import imgUrl from './img.svg'
+document.getElementById('hero-img').style.background = `url("${imgUrl}")`
+```
+
+:::
+
### Explicit URL Imports
Assets that are not included in the internal list or in `assetsInclude`, can be explicitly imported as a URL using the `?url` suffix. This is useful, for example, to import [Houdini Paint Worklets](https://houdini.how/usage).
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import workletURL from 'extra-scalloped-border/worklet.js?url'
CSS.paintWorklet.addModule(workletURL)
```
@@ -43,7 +59,9 @@ CSS.paintWorklet.addModule(workletURL)
Assets can be imported as strings using the `?raw` suffix.
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import shaderString from './shader.glsl?raw'
```
@@ -51,19 +69,25 @@ import shaderString from './shader.glsl?raw'
Scripts can be imported as web workers with the `?worker` or `?sharedworker` suffix.
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Separate chunk in the production build
import Worker from './shader.js?worker'
const worker = new Worker()
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// sharedworker
import SharedWorker from './shader.js?sharedworker'
const sharedWorker = new SharedWorker()
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Inlined as base64 strings
import InlineWorker from './shader.js?worker&inline'
```
diff --git a/docs/guide/backend-integration.md b/docs/guide/backend-integration.md
index 6e391e48b23261..8509082bbdf2ea 100644
--- a/docs/guide/backend-integration.md
+++ b/docs/guide/backend-integration.md
@@ -8,7 +8,9 @@ If you need a custom integration, you can follow the steps in this guide to conf
1. In your Vite config, configure the entry and enable build manifest:
- ```js
+ ```js twoslash
+ import { defineConfig } from 'vite'
+ // ---cut---
// vite.config.js
export default defineConfig({
build: {
@@ -60,22 +62,36 @@ If you need a custom integration, you can follow the steps in this guide to conf
```json
{
- "main.js": {
- "file": "assets/main.4889e940.js",
- "src": "main.js",
+ "_shared-!~{003}~.js": {
+ "file": "assets/shared-ChJ_j-JJ.css",
+ "src": "_shared-!~{003}~.js"
+ },
+ "_shared-B7PI925R.js": {
+ "file": "assets/shared-B7PI925R.js",
+ "name": "shared",
+ "css": ["assets/shared-ChJ_j-JJ.css"]
+ },
+ "baz.js": {
+ "file": "assets/baz-B2H3sXNv.js",
+ "name": "baz",
+ "src": "baz.js",
+ "isDynamicEntry": true
+ },
+ "views/bar.js": {
+ "file": "assets/bar-gkvgaI9m.js",
+ "name": "bar",
+ "src": "views/bar.js",
"isEntry": true,
- "dynamicImports": ["views/foo.js"],
- "css": ["assets/main.b82dbe22.css"],
- "assets": ["assets/asset.0ab0f9cd.png"]
+ "imports": ["_shared-B7PI925R.js"],
+ "dynamicImports": ["baz.js"]
},
"views/foo.js": {
- "file": "assets/foo.869aea0d.js",
+ "file": "assets/foo-BRBmoGS9.js",
+ "name": "foo",
"src": "views/foo.js",
- "isDynamicEntry": true,
- "imports": ["_shared.83069a53.js"]
- },
- "_shared.83069a53.js": {
- "file": "assets/shared.83069a53.js"
+ "isEntry": true,
+ "imports": ["_shared-B7PI925R.js"],
+ "css": ["assets/foo-5UjPuW-k.css"]
}
}
```
@@ -85,10 +101,54 @@ If you need a custom integration, you can follow the steps in this guide to conf
- For non entry chunks, the key is the base name of the generated file prefixed with `_`.
- Chunks will contain information on its static and dynamic imports (both are keys that map to the corresponding chunk in the manifest), and also its corresponding CSS and asset files (if any).
- You can use this file to render links or preload directives with hashed filenames (note: the syntax here is for explanation only, substitute with your server templating language):
+4. You can use this file to render links or preload directives with hashed filenames.
+
+ Here is an example HTML template to render the proper links. The syntax here is for
+ explanation only, substitute with your server templating language. The `importedChunks`
+ function is for illustration and isn't provided by Vite.
```html
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+ ```
+
+ Specifically, a backend generating HTML should include the following tags given a manifest
+ file and an entry point:
+
+ - A `` tag for each file in the entry point chunk's `css` list
+ - Recursively follow all chunks in the entry point's `imports` list and include a
+ `` tag for each CSS file of each imported chunk.
+ - A tag for the `file` key of the entry point chunk (`
+
+
+ ```
+
+ While the following should be included for the entry point `views/bar.js`:
+
+ ```html
+
+
+
+
```
diff --git a/docs/guide/build.md b/docs/guide/build.md
index 1ce6aeb6f7580d..6c4f2a1e5523ab 100644
--- a/docs/guide/build.md
+++ b/docs/guide/build.md
@@ -13,7 +13,7 @@ The production bundle assumes support for modern JavaScript. By default, Vite ta
You can specify custom targets via the [`build.target` config option](/config/build-options.md#build-target), where the lowest target is `es2015`.
-Note that by default, Vite only handles syntax transforms and **does not cover polyfills**. You can check out [Polyfill.io](https://polyfill.io/) which is a service that automatically generates polyfill bundles based on the user's browser UserAgent string.
+Note that by default, Vite only handles syntax transforms and **does not cover polyfills**. You can check out https://cdnjs.cloudflare.com/polyfill/ which automatically generates polyfill bundles based on the user's browser UserAgent string.
Legacy browsers can be supported via [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy), which will automatically generate legacy chunks and corresponding ES language feature polyfills. The legacy chunks are conditionally loaded only in browsers that do not have native ESM support.
@@ -34,7 +34,6 @@ For advanced base path control, check out [Advanced Base Options](#advanced-base
The build can be customized via various [build config options](/config/build-options.md). Specifically, you can directly adjust the underlying [Rollup options](https://rollupjs.org/configuration-options/) via `build.rollupOptions`:
```js
-// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
@@ -48,21 +47,19 @@ For example, you can specify multiple Rollup outputs with plugins that are only
## Chunking Strategy
-You can configure how chunks are split using `build.rollupOptions.output.manualChunks` (see [Rollup docs](https://rollupjs.org/configuration-options/#output-manualchunks)). Until Vite 2.8, the default chunking strategy divided the chunks into `index` and `vendor`. It is a good strategy for some SPAs, but it is hard to provide a general solution for every Vite target use case. From Vite 2.9, `manualChunks` is no longer modified by default. You can continue to use the Split Vendor Chunk strategy by adding the `splitVendorChunkPlugin` in your config file:
+You can configure how chunks are split using `build.rollupOptions.output.manualChunks` (see [Rollup docs](https://rollupjs.org/configuration-options/#output-manualchunks)). If you use a framework, refer to their documentation for configuring how chunks are splitted.
-```js
-// vite.config.js
-import { splitVendorChunkPlugin } from 'vite'
-export default defineConfig({
- plugins: [splitVendorChunkPlugin()],
+## Load Error Handling
+
+Vite emits `vite:preloadError` event when it fails to load dynamic imports. `event.payload` contains the original import error. If you call `event.preventDefault()`, the error will not be thrown.
+
+```js twoslash
+window.addEventListener('vite:preloadError', (event) => {
+ window.location.reload() // for example, refresh the page
})
```
-This strategy is also provided as a `splitVendorChunk({ cache: SplitVendorChunkCache })` factory, in case composition with custom logic is needed. `cache.reset()` needs to be called at `buildStart` for build watch mode to work correctly in this case.
-
-::: warning
-You should use `build.rollupOptions.output.manualChunks` function form when using this plugin. If the object form is used, the plugin won't have any effect.
-:::
+When a new deployment occurs, the hosting service may delete the assets from previous deployments. As a result, a user who visited your site before the new deployment might encounter an import error. This error happens because the assets running on that user's device are outdated and it tries to import the corresponding old chunk, which is deleted. This event is useful for addressing this situation.
## Rebuild on files changes
@@ -99,7 +96,7 @@ During dev, simply navigate or link to `/nested/` - it works as expected, just l
During build, all you need to do is to specify multiple `.html` files as entry points:
-```js
+```js twoslash
// vite.config.js
import { resolve } from 'path'
import { defineConfig } from 'vite'
@@ -126,7 +123,7 @@ When you are developing a browser-oriented library, you are likely spending most
When it is time to bundle your library for distribution, use the [`build.lib` config option](/config/build-options.md#build-lib). Make sure to also externalize any dependencies that you do not want to bundle into your library, e.g. `vue` or `react`:
-```js
+```js twoslash
// vite.config.js
import { resolve } from 'path'
import { defineConfig } from 'vite'
@@ -219,7 +216,7 @@ If the `package.json` does not contain `"type": "module"`, Vite will generate di
:::
::: tip Environment Variables
-In library mode, all `import.meta.env.*` usage are statically replaced when building for production. However, `process.env.*` usage are not, so that consumers of your library can dynamically change it. If this is undesirable, you can use `define: { 'process.env.NODE_ENV': '"production"' }` for example to statically replace them.
+In library mode, all [`import.meta.env.*`](./env-and-mode.md) usage are statically replaced when building for production. However, `process.env.*` usage are not, so that consumers of your library can dynamically change it. If this is undesirable, you can use `define: { 'process.env.NODE_ENV': '"production"' }` for example to statically replace them, or use [`esm-env`](https://github.com/benmccann/esm-env) for better compatibility with bundlers and runtimes.
:::
::: warning Advanced Usage
@@ -241,32 +238,45 @@ A user may choose to deploy in three different paths:
A single static [base](#public-base-path) isn't enough in these scenarios. Vite provides experimental support for advanced base options during build, using `experimental.renderBuiltUrl`.
-```ts
+```ts twoslash
+import type { UserConfig } from 'vite'
+// prettier-ignore
+const config: UserConfig = {
+// ---cut-before---
experimental: {
- renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {
+ renderBuiltUrl(filename, { hostType }) {
if (hostType === 'js') {
return { runtime: `window.__toCdnUrl(${JSON.stringify(filename)})` }
} else {
return { relative: true }
}
- }
+ },
+},
+// ---cut-after---
}
```
If the hashed assets and public files aren't deployed together, options for each group can be defined independently using asset `type` included in the second `context` param given to the function.
-```ts
+```ts twoslash
+import type { UserConfig } from 'vite'
+import path from 'node:path'
+// prettier-ignore
+const config: UserConfig = {
+// ---cut-before---
experimental: {
- renderBuiltUrl(filename: string, { hostId, hostType, type }: { hostId: string, hostType: 'js' | 'css' | 'html', type: 'public' | 'asset' }) {
+ renderBuiltUrl(filename, { hostId, hostType, type }) {
if (type === 'public') {
return 'https://www.domain.com/' + filename
- }
- else if (path.extname(hostId) === '.js') {
+ } else if (path.extname(hostId) === '.js') {
return { runtime: `window.__assetsPath(${JSON.stringify(filename)})` }
- }
- else {
+ } else {
return 'https://cdn.domain.com/assets/' + filename
}
- }
+ },
+},
+// ---cut-after---
}
```
+
+Note that the `filename` passed is a decoded URL, and if the function returns a URL string, it should also be decoded. Vite will handle the encoding automatically when rendering the URLs. If an object with `runtime` is returned, encoding should be handled yourself where needed as the runtime code will be rendered as is.
diff --git a/docs/guide/cli.md b/docs/guide/cli.md
index 08134c4c839a8b..8256f0811ddf29 100644
--- a/docs/guide/cli.md
+++ b/docs/guide/cli.md
@@ -4,7 +4,7 @@
### `vite`
-Start Vite dev server in the current directory.
+Start Vite dev server in the current directory. `vite dev` and `vite serve` are aliases for `vite`.
#### Usage
@@ -58,7 +58,6 @@ vite build [root]
| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--manifest [name]` | Emit build manifest json (`boolean \| string`) |
| `--ssrManifest [name]` | Emit ssr manifest json (`boolean \| string`) |
-| `--force` | Force the optimizer to ignore the cache and re-bundle (experimental)(`boolean`) |
| `--emptyOutDir` | Force empty outDir when it's outside of root (`boolean`) |
| `-w, --watch` | Rebuilds when modules have changed on disk (`boolean`) |
| `-c, --config ` | Use specified config file (`string`) |
diff --git a/docs/guide/dep-pre-bundling.md b/docs/guide/dep-pre-bundling.md
index 0bc25b6e69ff1e..e387a6ae1b8a48 100644
--- a/docs/guide/dep-pre-bundling.md
+++ b/docs/guide/dep-pre-bundling.md
@@ -37,7 +37,9 @@ In a monorepo setup, a dependency may be a linked package from the same repo. Vi
However, this requires the linked dep to be exported as ESM. If not, you can add the dependency to [`optimizeDeps.include`](/config/dep-optimization-options.md#optimizedeps-include) and [`build.commonjsOptions.include`](/config/build-options.md#build-commonjsoptions) in your config.
-```js
+```js twoslash
+import { defineConfig } from 'vite'
+// ---cut---
export default defineConfig({
optimizeDeps: {
include: ['linked-dep'],
@@ -60,7 +62,7 @@ A typical use case for `optimizeDeps.include` or `optimizeDeps.exclude` is when
Both `include` and `exclude` can be used to deal with this. If the dependency is large (with many internal modules) or is CommonJS, then you should include it; If the dependency is small and is already valid ESM, you can exclude it and let the browser load it directly.
-You can further customize esbuild too with the [`optimizeDeps.esbuildOptions` option](/config/dep-optimization-options.md#optimizedeps-esbuildoptions). For example, adding an esbuild plugin to handle special files in dependencies.
+You can further customize esbuild too with the [`optimizeDeps.esbuildOptions` option](/config/dep-optimization-options.md#optimizedeps-esbuildoptions). For example, adding an esbuild plugin to handle special files in dependencies or changing the [build `target`](https://esbuild.github.io/api/#target).
## Caching
diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md
index 888b516821b7b4..7c0c58190c9db6 100644
--- a/docs/guide/env-and-mode.md
+++ b/docs/guide/env-and-mode.md
@@ -2,7 +2,7 @@
## Env Variables
-Vite exposes env variables on the special **`import.meta.env`** object. Some built-in variables are available in all cases:
+Vite exposes env variables on the special **`import.meta.env`** object, which are statically replaced at build time. Some built-in variables are available in all cases:
- **`import.meta.env.MODE`**: {string} the [mode](#modes) the app is running in.
@@ -46,10 +46,15 @@ DB_PASSWORD=foobar
Only `VITE_SOME_KEY` will be exposed as `import.meta.env.VITE_SOME_KEY` to your client source code, but `DB_PASSWORD` will not.
```js
-console.log(import.meta.env.VITE_SOME_KEY) // 123
+console.log(import.meta.env.VITE_SOME_KEY) // "123"
console.log(import.meta.env.DB_PASSWORD) // undefined
```
+:::tip Env parsing
+
+As shown above, `VITE_SOME_KEY` is a number but returns a string when parsed. The same would also happen for boolean env variables. Make sure to convert to the desired type when using it in your code.
+:::
+
Also, Vite uses [dotenv-expand](https://github.com/motdotla/dotenv-expand) to expand variables out of the box. To learn more about the syntax, check out [their docs](https://github.com/motdotla/dotenv-expand#what-rules-does-the-expansion-engine-follow).
Note that if you want to use `$` inside your environment value, you have to escape it with `\`.
@@ -74,7 +79,7 @@ If you want to customize the env variables prefix, see the [envPrefix](/config/s
By default, Vite provides type definitions for `import.meta.env` in [`vite/client.d.ts`](https://github.com/vitejs/vite/blob/main/packages/vite/client.d.ts). While you can define more custom env variables in `.env.[mode]` files, you may want to get TypeScript IntelliSense for user-defined env variables that are prefixed with `VITE_`.
-To achieve this, you can create an `env.d.ts` in `src` directory, then augment `ImportMetaEnv` like this:
+To achieve this, you can create an `vite-env.d.ts` in `src` directory, then augment `ImportMetaEnv` like this:
```typescript
///
@@ -89,7 +94,7 @@ interface ImportMeta {
}
```
-If your code relies on types from browser environments such as [DOM](https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts) and [WebWorker](https://github.com/microsoft/TypeScript/blob/main/lib/lib.webworker.d.ts), you can update the [lib](https://www.typescriptlang.org/tsconfig#lib) field in `tsconfig.json`.
+If your code relies on types from browser environments such as [DOM](https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts) and [WebWorker](https://github.com/microsoft/TypeScript/blob/main/src/lib/webworker.generated.d.ts), you can update the [lib](https://www.typescriptlang.org/tsconfig#lib) field in `tsconfig.json`.
```json
{
@@ -97,6 +102,11 @@ If your code relies on types from browser environments such as [DOM](https://git
}
```
+:::warning Imports will break type augmentation
+
+If the `ImportMetaEnv` augmentation does not work, make sure you do not have any `import` statements in `vite-env.d.ts`. See the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/2/modules.html#how-javascript-modules-are-defined) for more information.
+:::
+
## HTML Env Replacement
Vite also supports replacing env variables in HTML files. Any properties in `import.meta.env` can be used in HTML files with a special `%ENV_NAME%` syntax:
@@ -108,6 +118,8 @@ Vite also supports replacing env variables in HTML files. Any properties in `imp
If the env doesn't exist in `import.meta.env`, e.g. `%NON_EXISTENT%`, it will be ignored and not replaced, unlike `import.meta.env.NON_EXISTENT` in JS where it's replaced as `undefined`.
+Given that Vite is used by many frameworks, it is intentionally unopinionated about complex replacements like conditionals. Vite can be extended using [an existing userland plugin](https://github.com/vitejs/awesome-vite#transformers) or a custom plugin that implements the [`transformIndexHtml` hook](./api-plugin#transformindexhtml).
+
## Modes
By default, the dev server (`dev` command) runs in `development` mode and the `build` command runs in `production` mode.
@@ -140,3 +152,35 @@ As `vite build` runs a production build by default, you can also change this and
# .env.testing
NODE_ENV=development
```
+
+## NODE_ENV and Modes
+
+It's important to note that `NODE_ENV` (`process.env.NODE_ENV`) and modes are two different concepts. Here's how different commands affect the `NODE_ENV` and mode:
+
+| Command | NODE_ENV | Mode |
+| ---------------------------------------------------- | --------------- | --------------- |
+| `vite build` | `"production"` | `"production"` |
+| `vite build --mode development` | `"production"` | `"development"` |
+| `NODE_ENV=development vite build` | `"development"` | `"production"` |
+| `NODE_ENV=development vite build --mode development` | `"development"` | `"development"` |
+
+The different values of `NODE_ENV` and mode also reflect on its corresponding `import.meta.env` properties:
+
+| Command | `import.meta.env.PROD` | `import.meta.env.DEV` |
+| ---------------------- | ---------------------- | --------------------- |
+| `NODE_ENV=production` | `true` | `false` |
+| `NODE_ENV=development` | `false` | `true` |
+| `NODE_ENV=other` | `false` | `true` |
+
+| Command | `import.meta.env.MODE` |
+| -------------------- | ---------------------- |
+| `--mode production` | `"production"` |
+| `--mode development` | `"development"` |
+| `--mode staging` | `"staging"` |
+
+:::tip `NODE_ENV` in `.env` files
+
+`NODE_ENV=...` can be set in the command, and also in your `.env` file. If `NODE_ENV` is specified in a `.env.[mode]` file, the mode can be used to control its value. However, both `NODE_ENV` and modes remain as two different concepts.
+
+The main benefit with `NODE_ENV=...` in the command is that it allows Vite to detect the value early. It also allows you to read `process.env.NODE_ENV` in your Vite config as Vite can only load the env files once the config is evaluated.
+:::
diff --git a/docs/guide/features.md b/docs/guide/features.md
index 6b195cd5ec41cb..75940b8d17310c 100644
--- a/docs/guide/features.md
+++ b/docs/guide/features.md
@@ -1,6 +1,6 @@
# Features
-At the very basic level, developing using Vite is not that much different from using a static file server. However, Vite provides many enhancements over native ESM imports to support various features that are typically seen in bundler-based setups.
+At the very basic level, developing using Vite is not that different from using a static file server. However, Vite provides many enhancements over native ESM imports to support various features that are typically seen in bundler-based setups.
## NPM Dependency Resolving and Pre-Bundling
@@ -65,7 +65,7 @@ It is because `esbuild` only performs transpilation without type information, it
You must set `"isolatedModules": true` in your `tsconfig.json` under `compilerOptions`, so that TS will warn you against the features that do not work with isolated transpilation.
-However, some libraries (e.g. [`vue`](https://github.com/vuejs/core/issues/1228)) don't work well with `"isolatedModules": true`. You can use `"skipLibCheck": true` to temporarily suppress the errors until it is fixed upstream.
+If a dependency doesn't work well with `"isolatedModules": true`. You can use `"skipLibCheck": true` to temporarily suppress the errors until it is fixed upstream.
#### `useDefineForClassFields`
@@ -111,7 +111,9 @@ As such, it is recommended to set `target` to `ESNext` or `ES2022` or newer, or
- [`experimentalDecorators`](https://www.typescriptlang.org/tsconfig#experimentalDecorators)
- [`alwaysStrict`](https://www.typescriptlang.org/tsconfig#alwaysStrict)
-If migrating your codebase to `"isolatedModules": true` is an insurmountable effort, you may be able to get around it with a third-party plugin such as [rollup-plugin-friendly-type-imports](https://www.npmjs.com/package/rollup-plugin-friendly-type-imports). However, this approach is not officially supported by Vite.
+::: tip `skipLibCheck`
+Vite starter templates have `"skipLibCheck": "true"` by default to avoid typechecking dependencies, as they may choose to only support specific versions and configurations of TypeScript. You can learn more at [vuejs/vue-cli#5688](https://github.com/vuejs/vue-cli/pull/5688).
+:::
### Client Types
@@ -172,9 +174,9 @@ Vite provides first-class Vue support:
Vue users should use the official [@vitejs/plugin-vue-jsx](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx) plugin, which provides Vue 3 specific features including HMR, global component resolving, directives and slots.
-If not using JSX with React or Vue, custom `jsxFactory` and `jsxFragment` can be configured using the [`esbuild` option](/config/shared-options.md#esbuild). For example for Preact:
+If using JSX without React or Vue, custom `jsxFactory` and `jsxFragment` can be configured using the [`esbuild` option](/config/shared-options.md#esbuild). For example for Preact:
-```js
+```js twoslash
// vite.config.js
import { defineConfig } from 'vite'
@@ -190,7 +192,7 @@ More details in [esbuild docs](https://esbuild.github.io/content-types/#jsx).
You can inject the JSX helpers using `jsxInject` (which is a Vite-only option) to avoid manual imports:
-```js
+```js twoslash
// vite.config.js
import { defineConfig } from 'vite'
@@ -228,7 +230,9 @@ Any CSS file ending with `.module.css` is considered a [CSS modules file](https:
}
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import classes from './example.module.css'
document.getElementById('foo').className = classes.red
```
@@ -237,7 +241,9 @@ CSS modules behavior can be configured via the [`css.modules` option](/config/sh
If `css.modules.localsConvention` is set to enable camelCase locals (e.g. `localsConvention: 'camelCaseOnly'`), you can also use named imports:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// .apply-color -> applyColor
import { applyColor } from './example.module.css'
document.getElementById('foo').className = applyColor
@@ -272,7 +278,9 @@ You can also use CSS modules combined with pre-processors by prepending `.module
The automatic injection of CSS contents can be turned off via the `?inline` query parameter. In this case, the processed CSS string is returned as the module's default export as usual, but the styles aren't injected to the page.
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import './foo.css' // will be injected into the page
import otherStyles from './bar.css?inline' // will not be injected
```
@@ -289,7 +297,7 @@ Starting from Vite 4.4, there is experimental support for [Lightning CSS](https:
npm add -D lightningcss
```
-If enabled, CSS files will be processed by Lightning CSS instead of PostCSS. To configure it, you can pass Lightning CSS options to the [`css.lightingcss`](../config/shared-options.md#css-lightningcss) config option.
+If enabled, CSS files will be processed by Lightning CSS instead of PostCSS. To configure it, you can pass Lightning CSS options to the [`css.lightningcss`](../config/shared-options.md#css-lightningcss) config option.
To configure CSS Modules, you'll use [`css.lightningcss.cssModules`](https://lightningcss.dev/css-modules.html) instead of [`css.modules`](../config/shared-options.md#css-modules) (which configures the way PostCSS handles CSS modules).
@@ -303,29 +311,39 @@ By default, Vite uses esbuild to minify CSS. Lightning CSS can also be used as t
Importing a static asset will return the resolved public URL when it is served:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
```
Special queries can modify how assets are loaded:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Explicitly load assets as URL
import assetAsURL from './asset.js?url'
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Load assets as strings
import assetAsString from './shader.glsl?raw'
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Load Web Workers
import Worker from './worker.js?worker'
```
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// Web Workers inlined as base64 strings at build time
import InlineWorker from './worker.js?worker&inline'
```
@@ -336,7 +354,9 @@ More details in [Static Asset Handling](./assets).
JSON files can be directly imported - named imports are also supported:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
// import the entire object
import json from './example.json'
// import a root field as named exports - helps with tree-shaking!
@@ -347,7 +367,9 @@ import { field } from './example.json'
Vite supports importing multiple modules from the file system via the special `import.meta.glob` function:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob('./dir/*.js')
```
@@ -373,7 +395,9 @@ for (const path in modules) {
Matched files are by default lazy-loaded via dynamic import and will be split into separate chunks during build. If you'd rather import all the modules directly (e.g. relying on side-effects in these modules to be applied first), you can pass `{ eager: true }` as the second argument:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob('./dir/*.js', { eager: true })
```
@@ -389,31 +413,13 @@ const modules = {
}
```
-### Glob Import As
-
-`import.meta.glob` also supports importing files as strings (similar to [Importing Asset as String](https://vitejs.dev/guide/assets.html#importing-asset-as-string)) with the [Import Reflection](https://github.com/tc39/proposal-import-reflection) syntax:
-
-```js
-const modules = import.meta.glob('./dir/*.js', { as: 'raw', eager: true })
-```
-
-The above will be transformed into the following:
-
-```js
-// code produced by vite
-const modules = {
- './dir/foo.js': 'export default "foo"\n',
- './dir/bar.js': 'export default "bar"\n',
-}
-```
-
-`{ as: 'url' }` is also supported for loading assets as URLs.
-
### Multiple Patterns
The first argument can be an array of globs, for example
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob(['./dir/*.js', './another/*.js'])
```
@@ -421,7 +427,9 @@ const modules = import.meta.glob(['./dir/*.js', './another/*.js'])
Negative glob patterns are also supported (prefixed with `!`). To ignore some files from the result, you can add exclude glob patterns to the first argument:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob(['./dir/*.js', '!**/bar.js'])
```
@@ -436,7 +444,9 @@ const modules = {
It's possible to only import parts of the modules with the `import` options.
-```ts
+```ts twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob('./dir/*.js', { import: 'setup' })
```
@@ -450,7 +460,9 @@ const modules = {
When combined with `eager` it's even possible to have tree-shaking enabled for those modules.
-```ts
+```ts twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob('./dir/*.js', {
import: 'setup',
eager: true,
@@ -469,7 +481,9 @@ const modules = {
Set `import` to `default` to import the default export.
-```ts
+```ts twoslash
+import 'vite/client'
+// ---cut---
const modules = import.meta.glob('./dir/*.js', {
import: 'default',
eager: true,
@@ -488,22 +502,43 @@ const modules = {
#### Custom Queries
-You can also use the `query` option to provide custom queries to imports for other plugins to consume.
+You can also use the `query` option to provide queries to imports, for example, to import assets [as a string](https://vitejs.dev/guide/assets.html#importing-asset-as-string) or [as a url](https://vitejs.dev/guide/assets.html#importing-asset-as-url):
-```ts
-const modules = import.meta.glob('./dir/*.js', {
- query: { foo: 'bar', bar: true },
+```ts twoslash
+import 'vite/client'
+// ---cut---
+const moduleStrings = import.meta.glob('./dir/*.svg', {
+ query: '?raw',
+ import: 'default',
+})
+const moduleUrls = import.meta.glob('./dir/*.svg', {
+ query: '?url',
+ import: 'default',
})
```
```ts
// code produced by vite:
-const modules = {
- './dir/foo.js': () => import('./dir/foo.js?foo=bar&bar=true'),
- './dir/bar.js': () => import('./dir/bar.js?foo=bar&bar=true'),
+const moduleStrings = {
+ './dir/foo.svg': () => import('./dir/foo.js?raw').then((m) => m['default']),
+ './dir/bar.svg': () => import('./dir/bar.js?raw').then((m) => m['default']),
+}
+const moduleUrls = {
+ './dir/foo.svg': () => import('./dir/foo.js?url').then((m) => m['default']),
+ './dir/bar.svg': () => import('./dir/bar.js?url').then((m) => m['default']),
}
```
+You can also provide custom queries for other plugins to consume:
+
+```ts twoslash
+import 'vite/client'
+// ---cut---
+const modules = import.meta.glob('./dir/*.js', {
+ query: { foo: 'bar', bar: true },
+})
+```
+
### Glob Import Caveats
Note that:
@@ -528,7 +563,9 @@ Note that variables only represent file names one level deep. If `file` is `'foo
Pre-compiled `.wasm` files can be imported with `?init`.
The default export will be an initialization function that returns a Promise of the [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Instance):
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import init from './example.wasm?init'
init().then((instance) => {
@@ -538,7 +575,10 @@ init().then((instance) => {
The init function can also take an importObject which is passed along to [`WebAssembly.instantiate`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiate) as its second argument:
-```js
+```js twoslash
+import 'vite/client'
+import init from './example.wasm?init'
+// ---cut---
init({
imports: {
someFunc: () => {
@@ -561,7 +601,9 @@ Use [`vite-plugin-wasm`](https://github.com/Menci/vite-plugin-wasm) or other com
If you need access to the `Module` object, e.g. to instantiate it multiple times, use an [explicit URL import](./assets#explicit-url-imports) to resolve the asset, and then perform the instantiation:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import wasmUrl from 'foo.wasm?url'
const main = async () => {
@@ -581,7 +623,9 @@ See the issue [Support wasm in SSR](https://github.com/vitejs/vite/issues/8882).
Here is an alternative, assuming the project base is the current directory:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import wasmUrl from 'foo.wasm?url'
import { readFile } from 'node:fs/promises'
@@ -615,32 +659,62 @@ const worker = new Worker(new URL('./worker.js', import.meta.url), {
})
```
+The worker detection will only work if the `new URL()` constructor is used directly inside the `new Worker()` declaration. Additionally, all options parameters must be static values (i.e. string literals).
+
### Import with Query Suffixes
A web worker script can be directly imported by appending `?worker` or `?sharedworker` to the import request. The default export will be a custom worker constructor:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import MyWorker from './worker?worker'
const worker = new MyWorker()
```
-The worker script can also use ESM `import` statements instead of `importScripts()`. **Note**: During dev this relies on [browser native support](https://caniuse.com/?search=module%20worker), but for the production build it is compiled away.
+The worker script can also use ESM `import` statements instead of `importScripts()`. **Note**: During development this relies on [browser native support](https://caniuse.com/?search=module%20worker), but for the production build it is compiled away.
By default, the worker script will be emitted as a separate chunk in the production build. If you wish to inline the worker as base64 strings, add the `inline` query:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import MyWorker from './worker?worker&inline'
```
If you wish to retrieve the worker as a URL, add the `url` query:
-```js
+```js twoslash
+import 'vite/client'
+// ---cut---
import MyWorker from './worker?worker&url'
```
See [Worker Options](/config/worker-options.md) for details on configuring the bundling of all workers.
+## Content Security Policy (CSP)
+
+To deploy CSP, certain directives or configs must be set due to Vite's internals.
+
+### [`'nonce-{RANDOM}'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#nonce-base64-value)
+
+When [`html.cspNonce`](/config/shared-options#html-cspnonce) is set, Vite adds a nonce attribute with the specified value to any `
diff --git a/docs/package.json b/docs/package.json
new file mode 100644
index 00000000000000..15ba56ec977f20
--- /dev/null
+++ b/docs/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "docs",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "docs": "vitepress dev",
+ "docs-build": "vitepress build",
+ "docs-serve": "vitepress serve"
+ },
+ "devDependencies": {
+ "@shikijs/vitepress-twoslash": "^1.10.0",
+ "@types/express": "^4.17.21",
+ "feed": "^4.2.2",
+ "vitepress": "1.2.3",
+ "vue": "^3.4.31"
+ }
+}
diff --git a/docs/public/handsontable.svg b/docs/public/handsontable.svg
new file mode 100644
index 00000000000000..865447fd65b4b4
--- /dev/null
+++ b/docs/public/handsontable.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/public/huly.svg b/docs/public/huly.svg
new file mode 100644
index 00000000000000..8a2631436c64c9
--- /dev/null
+++ b/docs/public/huly.svg
@@ -0,0 +1,6 @@
+
diff --git a/docs/public/logo-uwu.png b/docs/public/logo-uwu.png
new file mode 100644
index 00000000000000..e45e40af12a3e2
Binary files /dev/null and b/docs/public/logo-uwu.png differ
diff --git a/docs/public/nx.svg b/docs/public/nx.svg
new file mode 100644
index 00000000000000..b97dfb0e6381ee
--- /dev/null
+++ b/docs/public/nx.svg
@@ -0,0 +1,8 @@
+
diff --git a/docs/public/og-image-announcing-vite5-1.png b/docs/public/og-image-announcing-vite5-1.png
new file mode 100644
index 00000000000000..cebfc993994a50
Binary files /dev/null and b/docs/public/og-image-announcing-vite5-1.png differ
diff --git a/docs/public/og-image-announcing-vite5.png b/docs/public/og-image-announcing-vite5.png
new file mode 100644
index 00000000000000..56040e518ae1bf
Binary files /dev/null and b/docs/public/og-image-announcing-vite5.png differ
diff --git a/docs/public/transloadit-dark.svg b/docs/public/transloadit-dark.svg
new file mode 100644
index 00000000000000..f402f7a97d4d28
--- /dev/null
+++ b/docs/public/transloadit-dark.svg
@@ -0,0 +1,17 @@
+
diff --git a/docs/public/transloadit.svg b/docs/public/transloadit.svg
new file mode 100644
index 00000000000000..6033c48566d90e
--- /dev/null
+++ b/docs/public/transloadit.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/public/vite5-1-10K-modules-loading-time.png b/docs/public/vite5-1-10K-modules-loading-time.png
new file mode 100644
index 00000000000000..8c94ed9bf1f2ed
Binary files /dev/null and b/docs/public/vite5-1-10K-modules-loading-time.png differ
diff --git a/docs/releases.md b/docs/releases.md
index 31599406414403..4ea42cb0de5e0f 100644
--- a/docs/releases.md
+++ b/docs/releases.md
@@ -4,13 +4,7 @@ Vite releases follow [Semantic Versioning](https://semver.org/). You can see the
A full changelog of past releases is [available on GitHub](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md).
-::: tip note
-The next Vite Major release will happen after the Node 16 EOL in September.
-
-Check out the [Vite 5 discussion](https://github.com/vitejs/vite/discussions/12466) for more information.
-:::
-
-## Release Cycle
+## Release Cycle
Vite does not have a fixed release cycle.
@@ -24,7 +18,7 @@ The Vite team partners with the main projects in the ecosystem to test new Vite
## Semantic Versioning Edge Cases
-### TypeScript Definitions
+### TypeScript Definitions
We may ship incompatible changes to TypeScript definitions between minor versions. This is because:
@@ -40,16 +34,16 @@ We may ship incompatible changes to TypeScript definitions between minor version
Non-LTS Node.js versions (odd-numbered) are not tested as part of Vite's CI, but they should still work before their [EOL](https://endoflife.date/nodejs).
-## Pre Releases
+## Pre Releases
Minor releases typically go through a non-fixed number of beta releases. Major releases will go through an alpha phase and a beta phase.
Pre-releases allow early adopters and maintainers from the Ecosystem to do integration and stability testing, and provide feedback. Do not use pre-releases in production. All pre-releases are considered unstable and may ship breaking changes in between. Always pin to exact versions when using pre-releases.
-## Deprecations
+## Deprecations
We periodically deprecate features that have been superseded by better alternatives in Minor releases. Deprecated features will continue to work with a type or logged warning. They will be removed in the next major release after entering deprecated status. The [Migration Guide](https://vitejs.dev/guide/migration.html) for each major will list these removals and document an upgrade path for them.
-## Experimental Features
+## Experimental Features
-Some features are marked as experimental when released in a stable version of Vite. Experimental features allows us to gather real-world experience to influence their final design. The goal is to let users provide feedback by testing them in production. Experimental features themselves are considered unstable, and should only be used in a controlled manner. These features may change between Minors, so users must pin their Vite version when they rely on them.
+Some features are marked as experimental when released in a stable version of Vite. Experimental features allow us to gather real-world experience to influence their final design. The goal is to let users provide feedback by testing them in production. Experimental features themselves are considered unstable, and should only be used in a controlled manner. These features may change between Minors, so users must pin their Vite version when they rely on them. We will create [a GitHub discussion](https://github.com/vitejs/vite/discussions/categories/feedback?discussions_q=is%3Aopen+label%3Aexperimental+category%3AFeedback) for each experimental feature.
diff --git a/eslint.config.js b/eslint.config.js
new file mode 100644
index 00000000000000..0b103b51776cef
--- /dev/null
+++ b/eslint.config.js
@@ -0,0 +1,288 @@
+// @ts-check
+import { builtinModules, createRequire } from 'node:module'
+import eslint from '@eslint/js'
+import pluginN from 'eslint-plugin-n'
+import pluginImportX from 'eslint-plugin-import-x'
+import pluginRegExp from 'eslint-plugin-regexp'
+import tseslint from 'typescript-eslint'
+import globals from 'globals'
+
+const require = createRequire(import.meta.url)
+const pkg = require('./package.json')
+const pkgVite = require('./packages/vite/package.json')
+
+export default tseslint.config(
+ {
+ ignores: [
+ 'packages/create-vite/template-*',
+ '**/dist/**',
+ '**/fixtures/**',
+ '**/playground-temp/**',
+ '**/temp/**',
+ '**/.vitepress/cache/**',
+ '**/*.snap',
+ ],
+ },
+ eslint.configs.recommended,
+ ...tseslint.configs.recommended,
+ ...tseslint.configs.stylistic,
+ pluginRegExp.configs['flat/recommended'],
+ {
+ name: 'main',
+ languageOptions: {
+ parser: tseslint.parser,
+ parserOptions: {
+ sourceType: 'module',
+ ecmaVersion: 2022,
+ },
+ globals: {
+ ...globals.es2021,
+ ...globals.node,
+ },
+ },
+ plugins: {
+ n: pluginN,
+ 'import-x': pluginImportX,
+ },
+ rules: {
+ 'n/no-exports-assign': 'error',
+ 'n/no-unpublished-bin': 'error',
+ 'n/no-unsupported-features/es-builtins': 'error',
+ 'n/no-unsupported-features/node-builtins': 'error',
+ 'n/process-exit-as-throw': 'error',
+ 'n/hashbang': 'error',
+
+ eqeqeq: ['warn', 'always', { null: 'never' }],
+ 'no-debugger': ['error'],
+ 'no-empty': ['warn', { allowEmptyCatch: true }],
+ 'no-process-exit': 'off',
+ 'no-useless-escape': 'off',
+ 'prefer-const': [
+ 'warn',
+ {
+ destructuring: 'all',
+ },
+ ],
+
+ 'n/no-missing-require': [
+ 'error',
+ {
+ // for try-catching yarn pnp
+ allowModules: ['pnpapi', 'vite'],
+ tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'],
+ },
+ ],
+ 'n/no-extraneous-import': [
+ 'error',
+ {
+ allowModules: ['vite', 'less', 'sass', 'vitest', 'unbuild'],
+ },
+ ],
+ 'n/no-extraneous-require': [
+ 'error',
+ {
+ allowModules: ['vite'],
+ },
+ ],
+
+ '@typescript-eslint/ban-ts-comment': 'error',
+ '@typescript-eslint/ban-types': 'off', // TODO: we should turn this on in a new PR
+ '@typescript-eslint/explicit-module-boundary-types': [
+ 'error',
+ { allowArgumentsExplicitlyTypedAsAny: true },
+ ],
+ '@typescript-eslint/no-empty-function': [
+ 'error',
+ { allow: ['arrowFunctions'] },
+ ],
+ '@typescript-eslint/no-empty-interface': 'off',
+ '@typescript-eslint/no-explicit-any': 'off', // maybe we should turn this on in a new PR
+ 'no-extra-semi': 'off',
+ '@typescript-eslint/no-extra-semi': 'off', // conflicts with prettier
+ '@typescript-eslint/no-inferrable-types': 'off',
+ '@typescript-eslint/no-unused-vars': 'off', // maybe we should turn this on in a new PR
+ '@typescript-eslint/no-var-requires': 'off',
+ '@typescript-eslint/consistent-type-imports': [
+ 'error',
+ { prefer: 'type-imports', disallowTypeAnnotations: false },
+ ],
+ // disable rules set in @typescript-eslint/stylistic v6 that wasn't set in @typescript-eslint/recommended v5 and which conflict with current code
+ // maybe we should turn them on in a new PR
+ '@typescript-eslint/array-type': 'off',
+ '@typescript-eslint/ban-tslint-comment': 'off',
+ '@typescript-eslint/consistent-generic-constructors': 'off',
+ '@typescript-eslint/consistent-indexed-object-style': 'off',
+ '@typescript-eslint/consistent-type-definitions': 'off',
+ '@typescript-eslint/prefer-for-of': 'off',
+ '@typescript-eslint/prefer-function-type': 'off',
+
+ 'import-x/no-nodejs-modules': [
+ 'error',
+ { allow: builtinModules.map((mod) => `node:${mod}`) },
+ ],
+ 'import-x/no-duplicates': 'error',
+ 'import-x/order': 'error',
+ 'sort-imports': [
+ 'error',
+ {
+ ignoreCase: false,
+ ignoreDeclarationSort: true,
+ ignoreMemberSort: false,
+ memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
+ allowSeparatedGroups: false,
+ },
+ ],
+
+ 'regexp/no-contradiction-with-assertion': 'error',
+ // in some cases using explicit letter-casing is more performant than the `i` flag
+ 'regexp/use-ignore-case': 'off',
+ },
+ },
+ {
+ name: 'vite/globals',
+ files: ['packages/**/*.?([cm])[jt]s?(x)'],
+ ignores: ['**/__tests__/**'],
+ rules: {
+ 'no-restricted-globals': ['error', 'require', '__dirname', '__filename'],
+ },
+ },
+ {
+ name: 'vite/node',
+ files: ['packages/vite/src/node/**/*.?([cm])[jt]s?(x)'],
+ rules: {
+ 'no-console': ['error'],
+ 'n/no-restricted-require': [
+ 'error',
+ Object.keys(pkgVite.devDependencies).map((d) => ({
+ name: d,
+ message:
+ `devDependencies can only be imported using ESM syntax so ` +
+ `that they are included in the rollup bundle. If you are trying to ` +
+ `lazy load a dependency, use (await import('dependency')).default instead.`,
+ })),
+ ],
+ },
+ },
+ {
+ name: 'playground/enforce-esm',
+ files: ['playground/**/*.?([cm])[jt]s?(x)'],
+ ignores: [
+ 'playground/ssr-resolve/**',
+ 'playground/**/*{commonjs,cjs}*/**',
+ 'playground/**/*{commonjs,cjs}*',
+ 'playground/**/*dep*/**',
+ 'playground/resolve/browser-module-field2/index.web.js',
+ 'playground/resolve/browser-field/**',
+ 'playground/tailwind/**', // blocked by https://github.com/postcss/postcss-load-config/issues/239
+ ],
+ rules: {
+ 'import-x/no-commonjs': 'error',
+ },
+ },
+ {
+ name: 'playground/test',
+ files: ['playground/**/__tests__/**/*.?([cm])[jt]s?(x)'],
+ rules: {
+ // engine field doesn't exist in playgrounds
+ 'n/no-unsupported-features/es-builtins': [
+ 'error',
+ {
+ version: pkg.engines.node,
+ },
+ ],
+ 'n/no-unsupported-features/node-builtins': [
+ 'error',
+ {
+ version: pkg.engines.node,
+ // ideally we would like to allow all experimental features
+ // https://github.com/eslint-community/eslint-plugin-n/issues/199
+ ignores: ['fetch'],
+ },
+ ],
+ },
+ },
+
+ {
+ name: 'disables/vite/client',
+ files: ['packages/vite/src/client/**/*.?([cm])[jt]s?(x)'],
+ ignores: ['**/__tests__/**'],
+ rules: {
+ 'n/no-unsupported-features/node-builtins': 'off',
+ },
+ },
+ {
+ name: 'disables/vite/types',
+ files: [
+ 'packages/vite/src/types/**/*.?([cm])[jt]s?(x)',
+ 'packages/vite/scripts/**/*.?([cm])[jt]s?(x)',
+ '**/*.spec.ts',
+ ],
+ rules: {
+ 'n/no-extraneous-import': 'off',
+ },
+ },
+ {
+ name: 'disables/create-vite/templates',
+ files: [
+ 'packages/create-vite/template-*/**/*.?([cm])[jt]s?(x)',
+ '**/build.config.ts',
+ ],
+ rules: {
+ 'no-undef': 'off',
+ 'n/no-missing-import': 'off',
+ 'n/no-extraneous-import': 'off',
+ 'n/no-extraneous-require': 'off',
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
+ },
+ },
+ {
+ name: 'disables/playground',
+ files: ['playground/**/*.?([cm])[jt]s?(x)', 'docs/**/*.?([cm])[jt]s?(x)'],
+ rules: {
+ 'n/no-extraneous-import': 'off',
+ 'n/no-extraneous-require': 'off',
+ 'n/no-missing-import': 'off',
+ 'n/no-missing-require': 'off',
+ 'n/no-unsupported-features/es-builtins': 'off',
+ 'n/no-unsupported-features/node-builtins': 'off',
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
+ 'no-undef': 'off',
+ 'no-empty': 'off',
+ 'no-constant-condition': 'off',
+ '@typescript-eslint/no-empty-function': 'off',
+ },
+ },
+ {
+ name: 'disables/playground/tsconfig-json',
+ files: [
+ 'playground/tsconfig-json/**/*.?([cm])[jt]s?(x)',
+ 'playground/tsconfig-json-load-error/**/*.?([cm])[jt]s?(x)',
+ ],
+ ignores: ['**/__tests__/**'],
+ rules: {
+ '@typescript-eslint/ban-ts-comment': 'off',
+ },
+ },
+ {
+ name: 'disables/js',
+ files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
+ rules: {
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
+ },
+ },
+ {
+ name: 'disables/dts',
+ files: ['**/*.d.ts'],
+ rules: {
+ '@typescript-eslint/triple-slash-reference': 'off',
+ },
+ },
+ {
+ name: 'disables/test',
+ files: ['**/__tests__/**/*.?([cm])[jt]s?(x)'],
+ rules: {
+ 'no-console': 'off',
+ '@typescript-eslint/ban-ts-comment': 'off',
+ },
+ },
+)
diff --git a/netlify.toml b/netlify.toml
index d78254570def67..b8a4deadd38fbd 100644
--- a/netlify.toml
+++ b/netlify.toml
@@ -1,5 +1,5 @@
[build.environment]
- NODE_VERSION = "18"
+ NODE_VERSION = "20"
# don't need playwright for docs build
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"
[build]
diff --git a/package.json b/package.json
index a2f07dd2b200b3..1a3b2566830736 100644
--- a/package.json
+++ b/package.json
@@ -26,14 +26,13 @@
"test": "run-s test-unit test-serve test-build",
"test-serve": "vitest run -c vitest.config.e2e.ts",
"test-build": "VITE_TEST_BUILD=1 vitest run -c vitest.config.e2e.ts",
- "test-build-without-plugin-commonjs": "VITE_TEST_WITHOUT_PLUGIN_COMMONJS=1 pnpm test-build",
"test-unit": "vitest run",
"test-docs": "pnpm run docs-build",
"debug-serve": "VITE_DEBUG_SERVE=1 vitest run -c vitest.config.e2e.ts",
"debug-build": "VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 vitest run -c vitest.config.e2e.ts",
- "docs": "vitepress dev docs",
- "docs-build": "vitepress build docs",
- "docs-serve": "vitepress serve docs",
+ "docs": "pnpm --filter=docs run docs",
+ "docs-build": "pnpm --filter=docs run docs-build",
+ "docs-serve": "pnpm --filter=docs run docs-serve",
"build": "pnpm -r --filter='./packages/*' run build",
"dev": "pnpm -r --parallel --filter='./packages/*' run dev",
"release": "tsx scripts/release.ts",
@@ -41,51 +40,45 @@
"ci-docs": "run-s build docs-build"
},
"devDependencies": {
- "@babel/types": "^7.23.0",
- "@rollup/plugin-typescript": "^11.1.5",
- "@types/babel__core": "^7.20.3",
- "@types/babel__preset-env": "^7.9.4",
- "@types/convert-source-map": "^2.0.2",
- "@types/cross-spawn": "^6.0.4",
- "@types/debug": "^4.1.10",
- "@types/estree": "^1.0.3",
- "@types/etag": "^1.8.2",
- "@types/fs-extra": "^11.0.3",
- "@types/json-stable-stringify": "^1.0.35",
- "@types/less": "^3.0.5",
- "@types/micromatch": "^4.0.4",
- "@types/node": "^20.8.10",
- "@types/picomatch": "^2.3.2",
- "@types/sass": "~1.43.1",
- "@types/stylus": "^0.48.41",
- "@types/ws": "^8.5.8",
- "@typescript-eslint/eslint-plugin": "^6.9.0",
- "@typescript-eslint/parser": "^6.9.0",
+ "@eslint/js": "^9.6.0",
+ "@types/babel__core": "^7.20.5",
+ "@types/babel__preset-env": "^7.9.7",
+ "@types/convert-source-map": "^2.0.3",
+ "@types/cross-spawn": "^6.0.6",
+ "@types/debug": "^4.1.12",
+ "@types/estree": "^1.0.5",
+ "@types/etag": "^1.8.3",
+ "@types/fs-extra": "^11.0.4",
+ "@types/less": "^3.0.6",
+ "@types/micromatch": "^4.0.9",
+ "@types/node": "^20.14.9",
+ "@types/picomatch": "^2.3.4",
+ "@types/stylus": "^0.48.42",
+ "@types/ws": "^8.5.10",
"@vitejs/release-scripts": "^1.3.1",
- "conventional-changelog-cli": "^3.0.0",
- "eslint": "^8.52.0",
- "eslint-define-config": "^1.24.1",
- "eslint-plugin-import": "^2.29.0",
- "eslint-plugin-n": "^16.2.0",
- "eslint-plugin-regexp": "^2.1.1",
- "execa": "^8.0.1",
- "fs-extra": "^11.1.1",
- "lint-staged": "^15.0.2",
- "npm-run-all2": "^6.1.1",
- "picocolors": "^1.0.0",
- "playwright-chromium": "^1.39.0",
- "prettier": "3.0.3",
- "rimraf": "^5.0.5",
- "rollup": "^4.2.0",
- "simple-git-hooks": "^2.9.0",
- "tslib": "^2.6.2",
- "tsx": "^3.14.0",
+ "conventional-changelog-cli": "^5.0.0",
+ "eslint": "^9.6.0",
+ "eslint-plugin-import-x": "^0.5.3",
+ "eslint-plugin-n": "^17.9.0",
+ "eslint-plugin-regexp": "^2.6.0",
+ "execa": "^9.3.0",
+ "fs-extra": "^11.2.0",
+ "globals": "^15.7.0",
+ "lint-staged": "^15.2.7",
+ "npm-run-all2": "^6.2.0",
+ "picocolors": "^1.0.1",
+ "playwright-chromium": "^1.45.0",
+ "prettier": "3.3.2",
+ "rimraf": "^5.0.7",
+ "rollup": "^4.13.0",
+ "rollup-plugin-esbuild": "^6.1.1",
+ "simple-git-hooks": "^2.11.1",
+ "tslib": "^2.6.3",
+ "tsx": "^4.16.0",
"typescript": "^5.2.2",
- "unbuild": "^2.0.0",
+ "typescript-eslint": "^7.15.0",
"vite": "workspace:*",
- "vitepress": "1.0.0-rc.24",
- "vitest": "^0.34.6",
- "vue": "^3.3.7"
+ "vitest": "^1.6.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm exec lint-staged --concurrent false"
@@ -104,23 +97,16 @@
"eslint --cache --fix"
]
},
- "packageManager": "pnpm@8.10.2",
+ "packageManager": "pnpm@9.4.0",
"pnpm": {
"overrides": {
"vite": "workspace:*"
},
- "packageExtensions": {
- "acorn-walk": {
- "peerDependencies": {
- "acorn": "*"
- }
- }
- },
"patchedDependencies": {
- "chokidar@3.5.3": "patches/chokidar@3.5.3.patch",
- "sirv@2.0.3": "patches/sirv@2.0.3.patch",
- "dotenv-expand@10.0.0": "patches/dotenv-expand@10.0.0.patch",
- "postcss-load-config@4.0.1": "patches/postcss-load-config@4.0.1.patch"
+ "acorn@8.12.0": "patches/acorn@8.12.0.patch",
+ "chokidar@3.6.0": "patches/chokidar@3.6.0.patch",
+ "http-proxy@1.18.1": "patches/http-proxy@1.18.1.patch",
+ "sirv@2.0.4": "patches/sirv@2.0.4.patch"
},
"peerDependencyRules": {
"allowedVersions": {
diff --git a/packages/create-vite/CHANGELOG.md b/packages/create-vite/CHANGELOG.md
index 5afed0cd758d04..95896664ee87e8 100644
--- a/packages/create-vite/CHANGELOG.md
+++ b/packages/create-vite/CHANGELOG.md
@@ -1,3 +1,91 @@
+## 5.3.0 (2024-06-21)
+
+* fix(create-vite): revert eslint 9 upgrade in templates (#17511) ([86cf1b4](https://github.com/vitejs/vite/commit/86cf1b4)), closes [#17511](https://github.com/vitejs/vite/issues/17511)
+* fix(create-vite): update tsconfig with moduleDetection true (#17468) ([7b240e4](https://github.com/vitejs/vite/commit/7b240e4)), closes [#17468](https://github.com/vitejs/vite/issues/17468)
+* fix(deps): update all non-major dependencies (#16258) ([7caef42](https://github.com/vitejs/vite/commit/7caef42)), closes [#16258](https://github.com/vitejs/vite/issues/16258)
+* fix(deps): update all non-major dependencies (#16376) ([58a2938](https://github.com/vitejs/vite/commit/58a2938)), closes [#16376](https://github.com/vitejs/vite/issues/16376)
+* fix(deps): update all non-major dependencies (#16488) ([2d50be2](https://github.com/vitejs/vite/commit/2d50be2)), closes [#16488](https://github.com/vitejs/vite/issues/16488)
+* fix(deps): update all non-major dependencies (#16549) ([2d6a13b](https://github.com/vitejs/vite/commit/2d6a13b)), closes [#16549](https://github.com/vitejs/vite/issues/16549)
+* fix(deps): update all non-major dependencies (#16603) ([6711553](https://github.com/vitejs/vite/commit/6711553)), closes [#16603](https://github.com/vitejs/vite/issues/16603)
+* fix(deps): update all non-major dependencies (#16660) ([bf2f014](https://github.com/vitejs/vite/commit/bf2f014)), closes [#16660](https://github.com/vitejs/vite/issues/16660)
+* fix(deps): update all non-major dependencies (#17321) ([4a89766](https://github.com/vitejs/vite/commit/4a89766)), closes [#17321](https://github.com/vitejs/vite/issues/17321)
+* fix(deps): update all non-major dependencies (#17430) ([4453d35](https://github.com/vitejs/vite/commit/4453d35)), closes [#17430](https://github.com/vitejs/vite/issues/17430)
+* fix(deps): update all non-major dependencies (#17494) ([bf123f2](https://github.com/vitejs/vite/commit/bf123f2)), closes [#17494](https://github.com/vitejs/vite/issues/17494)
+* chore(create-vite): update IDE support instructions in helloworld components (#16605) ([a265282](https://github.com/vitejs/vite/commit/a265282)), closes [#16605](https://github.com/vitejs/vite/issues/16605)
+* chore(deps): update all non-major dependencies (#16325) ([a78e265](https://github.com/vitejs/vite/commit/a78e265)), closes [#16325](https://github.com/vitejs/vite/issues/16325)
+* chore(deps): update all non-major dependencies (#16722) ([b45922a](https://github.com/vitejs/vite/commit/b45922a)), closes [#16722](https://github.com/vitejs/vite/issues/16722)
+* chore(deps): update all non-major dependencies (#17373) ([f2d52f1](https://github.com/vitejs/vite/commit/f2d52f1)), closes [#17373](https://github.com/vitejs/vite/issues/17373)
+* chore(deps): update dependency eslint to v9 (#16661) ([6c10662](https://github.com/vitejs/vite/commit/6c10662)), closes [#16661](https://github.com/vitejs/vite/issues/16661)
+* chore(deps): update dependency execa to v9 (#16662) ([76d1642](https://github.com/vitejs/vite/commit/76d1642)), closes [#16662](https://github.com/vitejs/vite/issues/16662)
+* feat(create-vite): add help usage (#16390) ([1d9bfc0](https://github.com/vitejs/vite/commit/1d9bfc0)), closes [#16390](https://github.com/vitejs/vite/issues/16390)
+* feat(create-vite): use "solution" tsconfig so that vite.config.ts is type checked (#15913) ([cf3f40c](https://github.com/vitejs/vite/commit/cf3f40c)), closes [#15913](https://github.com/vitejs/vite/issues/15913)
+* docs(create-vite): link to Vue docs for IDE support info (#16225) ([520bb89](https://github.com/vitejs/vite/commit/520bb89)), closes [#16225](https://github.com/vitejs/vite/issues/16225)
+
+
+
+## 5.2.3 (2024-03-20)
+
+* docs: update volar name and remove takeover mode related docs (#16171) ([0a56177](https://github.com/vitejs/vite/commit/0a56177)), closes [#16171](https://github.com/vitejs/vite/issues/16171)
+* fix(create-vite): remove vue3 deprecated plugin (TypeScript Vue Plugin) (#16158) ([1645fc0](https://github.com/vitejs/vite/commit/1645fc0)), closes [#16158](https://github.com/vitejs/vite/issues/16158)
+* fix(create-vite): switch to default Remix template (#16203) ([ea480df](https://github.com/vitejs/vite/commit/ea480df)), closes [#16203](https://github.com/vitejs/vite/issues/16203)
+* chore(deps): update all non-major dependencies (#16186) ([842643d](https://github.com/vitejs/vite/commit/842643d)), closes [#16186](https://github.com/vitejs/vite/issues/16186)
+* chore(deps): update dependency vue-tsc to v2 (#16187) ([72104f6](https://github.com/vitejs/vite/commit/72104f6)), closes [#16187](https://github.com/vitejs/vite/issues/16187)
+
+
+
+## 5.2.2 (2024-03-11)
+
+* chore(deps): update all non-major dependencies (#16028) ([7cfe80d](https://github.com/vitejs/vite/commit/7cfe80d)), closes [#16028](https://github.com/vitejs/vite/issues/16028)
+* chore(deps): update all non-major dependencies (#16131) ([a862ecb](https://github.com/vitejs/vite/commit/a862ecb)), closes [#16131](https://github.com/vitejs/vite/issues/16131)
+* fix(create-vite): ts error in the svelte-ts template (#16031) ([ff4c834](https://github.com/vitejs/vite/commit/ff4c834)), closes [#16031](https://github.com/vitejs/vite/issues/16031)
+
+
+
+## 5.2.1 (2024-02-21)
+
+* fix(create-vite): remove tsc command from qwik template (#15982) ([5e05f10](https://github.com/vitejs/vite/commit/5e05f10)), closes [#15982](https://github.com/vitejs/vite/issues/15982)
+* fix(deps): update all non-major dependencies (#15959) ([571a3fd](https://github.com/vitejs/vite/commit/571a3fd)), closes [#15959](https://github.com/vitejs/vite/issues/15959)
+* fix(qwik template): change preview script (#15975) ([725589a](https://github.com/vitejs/vite/commit/725589a)), closes [#15975](https://github.com/vitejs/vite/issues/15975)
+* feat(create-vite): add custom remix option for React (#15995) ([f3b195c](https://github.com/vitejs/vite/commit/f3b195c)), closes [#15995](https://github.com/vitejs/vite/issues/15995)
+* chore(deps): update all non-major dependencies (#15874) ([d16ce5d](https://github.com/vitejs/vite/commit/d16ce5d)), closes [#15874](https://github.com/vitejs/vite/issues/15874)
+* chore(deps): update typescript-eslint monorepo to v7 (major) (#15960) ([7b9e927](https://github.com/vitejs/vite/commit/7b9e927)), closes [#15960](https://github.com/vitejs/vite/issues/15960)
+
+
+
+## 5.2.0 (2024-02-08)
+
+* fix(create-vite): turn off `react/jsx-no-target-blank` ESLint rule in React JS template (#15672) ([a6f39e8](https://github.com/vitejs/vite/commit/a6f39e8)), closes [#15672](https://github.com/vitejs/vite/issues/15672)
+* fix(deps): update all non-major dependencies (#15375) ([ab56227](https://github.com/vitejs/vite/commit/ab56227)), closes [#15375](https://github.com/vitejs/vite/issues/15375)
+* fix(deps): update all non-major dependencies (#15603) ([109fb80](https://github.com/vitejs/vite/commit/109fb80)), closes [#15603](https://github.com/vitejs/vite/issues/15603)
+* fix(deps): update all non-major dependencies (#15675) ([4d9363a](https://github.com/vitejs/vite/commit/4d9363a)), closes [#15675](https://github.com/vitejs/vite/issues/15675)
+* fix(deps): update all non-major dependencies (#15803) ([e0a6ef2](https://github.com/vitejs/vite/commit/e0a6ef2)), closes [#15803](https://github.com/vitejs/vite/issues/15803)
+* feat(create-vite): allow overwrite in command line (#15808) ([1882c73](https://github.com/vitejs/vite/commit/1882c73)), closes [#15808](https://github.com/vitejs/vite/issues/15808)
+* feat(create-vite): set "strict: true" in tsconfig.node.json (#15820) ([5e5ca7d](https://github.com/vitejs/vite/commit/5e5ca7d)), closes [#15820](https://github.com/vitejs/vite/issues/15820)
+* docs: changed bunx create-vite to bun create vite (#15646) ([f3c11bb](https://github.com/vitejs/vite/commit/f3c11bb)), closes [#15646](https://github.com/vitejs/vite/issues/15646)
+* chore(deps): update dependency @vitejs/plugin-vue to v5 (#15474) ([17857e7](https://github.com/vitejs/vite/commit/17857e7)), closes [#15474](https://github.com/vitejs/vite/issues/15474)
+
+
+
+## 5.1.0 (2023-12-12)
+
+* fix(deps): update all non-major dependencies (#15233) ([ad3adda](https://github.com/vitejs/vite/commit/ad3adda)), closes [#15233](https://github.com/vitejs/vite/issues/15233)
+* fix(deps): update all non-major dependencies (#15304) ([bb07f60](https://github.com/vitejs/vite/commit/bb07f60)), closes [#15304](https://github.com/vitejs/vite/issues/15304)
+* feat(cli): allow initializing non-empty directory (#15272) ([00669e1](https://github.com/vitejs/vite/commit/00669e1)), closes [#15272](https://github.com/vitejs/vite/issues/15272)
+* chore(deps): update all non-major dependencies (#15145) ([7ff2c0a](https://github.com/vitejs/vite/commit/7ff2c0a)), closes [#15145](https://github.com/vitejs/vite/issues/15145)
+
+
+
+## 5.0.0 (2023-11-16)
+
+* feat(create-vite): update templates for vite 5 (#15007) ([e208697](https://github.com/vitejs/vite/commit/e208697)), closes [#15007](https://github.com/vitejs/vite/issues/15007)
+* fix(create-vite): remove repeated styles in vue-template (#14766) ([0fed210](https://github.com/vitejs/vite/commit/0fed210)), closes [#14766](https://github.com/vitejs/vite/issues/14766)
+* fix(deps): update all non-major dependencies (#14729) ([d5d96e7](https://github.com/vitejs/vite/commit/d5d96e7)), closes [#14729](https://github.com/vitejs/vite/issues/14729)
+* fix(deps): update all non-major dependencies (#14883) ([e5094e5](https://github.com/vitejs/vite/commit/e5094e5)), closes [#14883](https://github.com/vitejs/vite/issues/14883)
+* fix(deps): update all non-major dependencies (#14961) ([0bb3995](https://github.com/vitejs/vite/commit/0bb3995)), closes [#14961](https://github.com/vitejs/vite/issues/14961)
+* chore(deps): update dependency eslint-plugin-react-refresh to ^0.4.4 (#14795) ([7881457](https://github.com/vitejs/vite/commit/7881457)), closes [#14795](https://github.com/vitejs/vite/issues/14795)
+
+
+
## 5.0.0-beta.1 (2023-10-19)
* chore(create-vite): update dependencies (#14698) ([bd82c30](https://github.com/vitejs/vite/commit/bd82c30)), closes [#14698](https://github.com/vitejs/vite/issues/14698)
diff --git a/packages/create-vite/README.md b/packages/create-vite/README.md
index 6d016ef5f4ed8c..a6f879fcb9e48d 100644
--- a/packages/create-vite/README.md
+++ b/packages/create-vite/README.md
@@ -26,7 +26,7 @@ $ pnpm create vite
With Bun:
```bash
-$ bunx create-vite
+$ bun create vite
```
Then follow the prompts!
@@ -44,7 +44,7 @@ yarn create vite my-vue-app --template vue
pnpm create vite my-vue-app --template vue
# Bun
-bunx create-vite my-vue-app --template vue
+bun create vite my-vue-app --template vue
```
Currently supported template presets include:
diff --git a/packages/create-vite/__tests__/cli.spec.ts b/packages/create-vite/__tests__/cli.spec.ts
index 0db7338415e75a..8f03bf7d2df0c0 100644
--- a/packages/create-vite/__tests__/cli.spec.ts
+++ b/packages/create-vite/__tests__/cli.spec.ts
@@ -1,5 +1,5 @@
import { join } from 'node:path'
-import type { ExecaSyncReturnValue, SyncOptions } from 'execa'
+import type { SyncOptions, SyncResult } from 'execa'
import { execaCommandSync } from 'execa'
import fs from 'fs-extra'
import { afterEach, beforeAll, expect, test } from 'vitest'
@@ -9,10 +9,10 @@ const CLI_PATH = join(__dirname, '..')
const projectName = 'test-app'
const genPath = join(__dirname, projectName)
-const run = (
+const run = (
args: string[],
- options: SyncOptions = {},
-): ExecaSyncReturnValue => {
+ options?: SO,
+): SyncResult => {
return execaCommandSync(`node ${CLI_PATH} ${args.join(' ')}`, options)
}
@@ -97,3 +97,21 @@ test('works with the -t alias', () => {
expect(stdout).toContain(`Scaffolding project in ${genPath}`)
expect(templateFiles).toEqual(generatedFiles)
})
+
+test('accepts command line override for --overwrite', () => {
+ createNonEmptyDir()
+ const { stdout } = run(['.', '--overwrite', 'ignore'], { cwd: genPath })
+ expect(stdout).not.toContain(`Current directory is not empty.`)
+})
+
+test('return help usage how to use create-vite', () => {
+ const { stdout } = run(['--help'], { cwd: __dirname })
+ const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
+ expect(stdout).toContain(message)
+})
+
+test('return help usage how to use create-vite with -h alias', () => {
+ const { stdout } = run(['--h'], { cwd: __dirname })
+ const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
+ expect(stdout).toContain(message)
+})
diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json
index bb671f55dc79d5..a3ac165c85201f 100644
--- a/packages/create-vite/package.json
+++ b/packages/create-vite/package.json
@@ -1,6 +1,6 @@
{
"name": "create-vite",
- "version": "5.0.0-beta.1",
+ "version": "5.3.0",
"type": "module",
"license": "MIT",
"author": "Evan You",
@@ -33,8 +33,8 @@
"homepage": "https://github.com/vitejs/vite/tree/main/packages/create-vite#readme",
"funding": "https://github.com/vitejs/vite?sponsor=1",
"devDependencies": {
- "@types/minimist": "^1.2.4",
- "@types/prompts": "^2.4.7",
+ "@types/minimist": "^1.2.5",
+ "@types/prompts": "^2.4.9",
"cross-spawn": "^7.0.3",
"kolorist": "^1.8.0",
"minimist": "^1.2.8",
diff --git a/packages/create-vite/src/index.ts b/packages/create-vite/src/index.ts
index 20212c337580dd..463c78cf669817 100755
--- a/packages/create-vite/src/index.ts
+++ b/packages/create-vite/src/index.ts
@@ -20,11 +20,36 @@ import {
// Avoids autoconversion to number of the project name by defining that the args
// non associated with an option ( _ ) needs to be parsed as a string. See #4606
const argv = minimist<{
- t?: string
template?: string
-}>(process.argv.slice(2), { string: ['_'] })
+ help?: boolean
+}>(process.argv.slice(2), {
+ default: { help: false },
+ alias: { h: 'help', t: 'template' },
+ string: ['_'],
+})
const cwd = process.cwd()
+// prettier-ignore
+const helpMessage = `\
+Usage: create-vite [OPTION]... [DIRECTORY]
+
+Create a new Vite project in JavaScript or TypeScript.
+With no arguments, start the CLI in interactive mode.
+
+Options:
+ -t, --template NAME use a specific template
+
+Available templates:
+${yellow ('vanilla-ts vanilla' )}
+${green ('vue-ts vue' )}
+${cyan ('react-ts react' )}
+${cyan ('react-swc-ts react-swc')}
+${magenta ('preact-ts preact' )}
+${lightRed ('lit-ts lit' )}
+${red ('svelte-ts svelte' )}
+${blue ('solid-ts solid' )}
+${lightBlue('qwik-ts qwik' )}`
+
type ColorFunc = (str: string | number) => string
type Framework = {
name: string
@@ -111,6 +136,12 @@ const FRAMEWORKS: Framework[] = [
display: 'JavaScript + SWC',
color: yellow,
},
+ {
+ name: 'custom-remix',
+ display: 'Remix ↗',
+ color: cyan,
+ customCommand: 'npm create remix@latest TARGET_DIR',
+ },
],
},
{
@@ -245,6 +276,12 @@ async function init() {
const argTargetDir = formatTargetDir(argv._[0])
const argTemplate = argv.template || argv.t
+ const help = argv.help
+ if (help) {
+ console.log(helpMessage)
+ return
+ }
+
let targetDir = argTargetDir || defaultTargetDir
const getProjectName = () =>
targetDir === '.' ? path.basename(path.resolve()) : targetDir
@@ -253,6 +290,10 @@ async function init() {
'projectName' | 'overwrite' | 'packageName' | 'framework' | 'variant'
>
+ prompts.override({
+ overwrite: argv.overwrite,
+ })
+
try {
result = await prompts(
[
@@ -267,17 +308,32 @@ async function init() {
},
{
type: () =>
- !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm',
+ !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'select',
name: 'overwrite',
message: () =>
(targetDir === '.'
? 'Current directory'
: `Target directory "${targetDir}"`) +
- ` is not empty. Remove existing files and continue?`,
+ ` is not empty. Please choose how to proceed:`,
+ initial: 0,
+ choices: [
+ {
+ title: 'Remove existing files and continue',
+ value: 'yes',
+ },
+ {
+ title: 'Cancel operation',
+ value: 'no',
+ },
+ {
+ title: 'Ignore files and continue',
+ value: 'ignore',
+ },
+ ],
},
{
- type: (_, { overwrite }: { overwrite?: boolean }) => {
- if (overwrite === false) {
+ type: (_, { overwrite }: { overwrite?: string }) => {
+ if (overwrite === 'no') {
throw new Error(red('✖') + ' Operation cancelled')
}
return null
@@ -342,7 +398,7 @@ async function init() {
const root = path.join(cwd, targetDir)
- if (overwrite) {
+ if (overwrite === 'yes') {
emptyDir(root)
} else if (!fs.existsSync(root)) {
fs.mkdirSync(root, { recursive: true })
@@ -393,7 +449,9 @@ async function init() {
const [command, ...args] = fullCustomCommand.split(' ')
// we replace TARGET_DIR here because targetDir may include a space
- const replacedArgs = args.map((arg) => arg.replace('TARGET_DIR', targetDir))
+ const replacedArgs = args.map((arg) =>
+ arg.replace('TARGET_DIR', () => targetDir),
+ )
const { status } = spawn.sync(command, replacedArgs, {
stdio: 'inherit',
})
@@ -524,7 +582,7 @@ function setupReactSwc(root: string, isTs: boolean) {
editFile(path.resolve(root, 'package.json'), (content) => {
return content.replace(
/"@vitejs\/plugin-react": ".+?"/,
- `"@vitejs/plugin-react-swc": "^3.3.2"`,
+ `"@vitejs/plugin-react-swc": "^3.5.0"`,
)
})
editFile(
diff --git a/packages/create-vite/template-lit-ts/package.json b/packages/create-vite/template-lit-ts/package.json
index 64bd3e38ccdff4..be7c7c9cc257ec 100644
--- a/packages/create-vite/template-lit-ts/package.json
+++ b/packages/create-vite/template-lit-ts/package.json
@@ -9,10 +9,10 @@
"preview": "vite preview"
},
"dependencies": {
- "lit": "^3.0.1"
+ "lit": "^3.1.4"
},
"devDependencies": {
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-lit-ts/tsconfig.json b/packages/create-vite/template-lit-ts/tsconfig.json
index 69e31ac92882e3..d689ddbd308a54 100644
--- a/packages/create-vite/template-lit-ts/tsconfig.json
+++ b/packages/create-vite/template-lit-ts/tsconfig.json
@@ -12,6 +12,7 @@
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
+ "moduleDetection": "force",
"noEmit": true,
/* Linting */
diff --git a/packages/create-vite/template-lit/package.json b/packages/create-vite/template-lit/package.json
index 81979702df847f..1a37fd91de72d2 100644
--- a/packages/create-vite/template-lit/package.json
+++ b/packages/create-vite/template-lit/package.json
@@ -9,9 +9,9 @@
"preview": "vite preview"
},
"dependencies": {
- "lit": "^3.0.1"
+ "lit": "^3.1.4"
},
"devDependencies": {
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-preact-ts/package.json b/packages/create-vite/template-preact-ts/package.json
index 95c5ff727f9e2c..c098b29eda13b8 100644
--- a/packages/create-vite/template-preact-ts/package.json
+++ b/packages/create-vite/template-preact-ts/package.json
@@ -5,15 +5,15 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
- "preact": "^10.18.1"
+ "preact": "^10.22.1"
},
"devDependencies": {
- "@preact/preset-vite": "^2.6.0",
+ "@preact/preset-vite": "^2.8.3",
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-preact-ts/tsconfig.app.json b/packages/create-vite/template-preact-ts/tsconfig.app.json
new file mode 100644
index 00000000000000..43648503db4c9e
--- /dev/null
+++ b/packages/create-vite/template-preact-ts/tsconfig.app.json
@@ -0,0 +1,32 @@
+{
+ "compilerOptions": {
+ "composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "module": "ESNext",
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "skipLibCheck": true,
+ "paths": {
+ "react": ["./node_modules/preact/compat/"],
+ "react-dom": ["./node_modules/preact/compat/"]
+ },
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "jsxImportSource": "preact",
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/create-vite/template-preact-ts/tsconfig.json b/packages/create-vite/template-preact-ts/tsconfig.json
index d13245791d3674..ea9d0cd8255683 100644
--- a/packages/create-vite/template-preact-ts/tsconfig.json
+++ b/packages/create-vite/template-preact-ts/tsconfig.json
@@ -1,30 +1,11 @@
{
- "compilerOptions": {
- "target": "ES2020",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "skipLibCheck": true,
- "paths": {
- "react": ["./node_modules/preact/compat/"],
- "react-dom": ["./node_modules/preact/compat/"]
+ "files": [],
+ "references": [
+ {
+ "path": "./tsconfig.app.json"
},
-
- /* Bundler mode */
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
- "jsx": "react-jsx",
- "jsxImportSource": "preact",
-
- /* Linting */
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- "include": ["src"],
- "references": [{ "path": "./tsconfig.node.json" }]
+ {
+ "path": "./tsconfig.node.json"
+ }
+ ]
}
diff --git a/packages/create-vite/template-preact-ts/tsconfig.node.json b/packages/create-vite/template-preact-ts/tsconfig.node.json
index 42872c59f5b01c..3afdd6e38438be 100644
--- a/packages/create-vite/template-preact-ts/tsconfig.node.json
+++ b/packages/create-vite/template-preact-ts/tsconfig.node.json
@@ -1,10 +1,13 @@
{
"compilerOptions": {
"composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noEmit": true
},
"include": ["vite.config.ts"]
}
diff --git a/packages/create-vite/template-preact/package.json b/packages/create-vite/template-preact/package.json
index fdf20eaecf1bd1..a0a553338694ac 100644
--- a/packages/create-vite/template-preact/package.json
+++ b/packages/create-vite/template-preact/package.json
@@ -9,10 +9,10 @@
"preview": "vite preview"
},
"dependencies": {
- "preact": "^10.18.1"
+ "preact": "^10.22.1"
},
"devDependencies": {
- "@preact/preset-vite": "^2.6.0",
- "vite": "^5.0.0-beta.13"
+ "@preact/preset-vite": "^2.8.3",
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-qwik-ts/package.json b/packages/create-vite/template-qwik-ts/package.json
index ef7f1a6a037c29..3da012571197c8 100644
--- a/packages/create-vite/template-qwik-ts/package.json
+++ b/packages/create-vite/template-qwik-ts/package.json
@@ -5,14 +5,15 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
- "preview": "vite preview"
+ "build": "tsc -b && vite build",
+ "preview": "serve dist"
},
"devDependencies": {
+ "serve": "^14.2.3",
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
},
"dependencies": {
- "@builder.io/qwik": "^1.2.15"
+ "@builder.io/qwik": "^1.6.0"
}
}
diff --git a/packages/create-vite/template-qwik-ts/tsconfig.app.json b/packages/create-vite/template-qwik-ts/tsconfig.app.json
new file mode 100644
index 00000000000000..2bf219f042afb7
--- /dev/null
+++ b/packages/create-vite/template-qwik-ts/tsconfig.app.json
@@ -0,0 +1,28 @@
+{
+ "compilerOptions": {
+ "composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "module": "ESNext",
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "jsxImportSource": "@builder.io/qwik",
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/create-vite/template-qwik-ts/tsconfig.json b/packages/create-vite/template-qwik-ts/tsconfig.json
index 9a262f041fc748..ea9d0cd8255683 100644
--- a/packages/create-vite/template-qwik-ts/tsconfig.json
+++ b/packages/create-vite/template-qwik-ts/tsconfig.json
@@ -1,26 +1,11 @@
{
- "compilerOptions": {
- "target": "ES2020",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "skipLibCheck": true,
-
- /* Bundler mode */
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
- "jsx": "react-jsx",
- "jsxImportSource": "@builder.io/qwik",
-
- /* Linting */
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- "include": ["src"],
- "references": [{ "path": "./tsconfig.node.json" }]
+ "files": [],
+ "references": [
+ {
+ "path": "./tsconfig.app.json"
+ },
+ {
+ "path": "./tsconfig.node.json"
+ }
+ ]
}
diff --git a/packages/create-vite/template-qwik-ts/tsconfig.node.json b/packages/create-vite/template-qwik-ts/tsconfig.node.json
index 42872c59f5b01c..3afdd6e38438be 100644
--- a/packages/create-vite/template-qwik-ts/tsconfig.node.json
+++ b/packages/create-vite/template-qwik-ts/tsconfig.node.json
@@ -1,10 +1,13 @@
{
"compilerOptions": {
"composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noEmit": true
},
"include": ["vite.config.ts"]
}
diff --git a/packages/create-vite/template-qwik/package.json b/packages/create-vite/template-qwik/package.json
index ef7f1a6a037c29..b8ef00283b68ec 100644
--- a/packages/create-vite/template-qwik/package.json
+++ b/packages/create-vite/template-qwik/package.json
@@ -5,14 +5,14 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
- "preview": "vite preview"
+ "build": "vite build",
+ "preview": "serve dist"
},
"devDependencies": {
- "typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "serve": "^14.2.3",
+ "vite": "^5.3.2"
},
"dependencies": {
- "@builder.io/qwik": "^1.2.15"
+ "@builder.io/qwik": "^1.6.0"
}
}
diff --git a/packages/create-vite/template-react-ts/package.json b/packages/create-vite/template-react-ts/package.json
index 9bc5e3858211d1..f5cf282df8a623 100644
--- a/packages/create-vite/template-react-ts/package.json
+++ b/packages/create-vite/template-react-ts/package.json
@@ -5,24 +5,24 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "build": "tsc -b && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
- "react": "^18.2.0",
- "react-dom": "^18.2.0"
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1"
},
"devDependencies": {
- "@types/react": "^18.2.33",
- "@types/react-dom": "^18.2.14",
- "@typescript-eslint/eslint-plugin": "^6.9.0",
- "@typescript-eslint/parser": "^6.9.0",
- "@vitejs/plugin-react": "^4.1.0",
- "eslint": "^8.52.0",
- "eslint-plugin-react-hooks": "^4.6.0",
- "eslint-plugin-react-refresh": "^0.4.4",
+ "@types/react": "^18.3.3",
+ "@types/react-dom": "^18.3.0",
+ "@typescript-eslint/eslint-plugin": "^7.15.0",
+ "@typescript-eslint/parser": "^7.15.0",
+ "@vitejs/plugin-react": "^4.3.1",
+ "eslint": "^8.57.0",
+ "eslint-plugin-react-hooks": "^4.6.2",
+ "eslint-plugin-react-refresh": "^0.4.7",
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-react-ts/tsconfig.app.json b/packages/create-vite/template-react-ts/tsconfig.app.json
new file mode 100644
index 00000000000000..d739292ae01436
--- /dev/null
+++ b/packages/create-vite/template-react-ts/tsconfig.app.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/create-vite/template-react-ts/tsconfig.json b/packages/create-vite/template-react-ts/tsconfig.json
index a7fc6fbf23de2a..ea9d0cd8255683 100644
--- a/packages/create-vite/template-react-ts/tsconfig.json
+++ b/packages/create-vite/template-react-ts/tsconfig.json
@@ -1,25 +1,11 @@
{
- "compilerOptions": {
- "target": "ES2020",
- "useDefineForClassFields": true,
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "module": "ESNext",
- "skipLibCheck": true,
-
- /* Bundler mode */
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
- "jsx": "react-jsx",
-
- /* Linting */
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- "include": ["src"],
- "references": [{ "path": "./tsconfig.node.json" }]
+ "files": [],
+ "references": [
+ {
+ "path": "./tsconfig.app.json"
+ },
+ {
+ "path": "./tsconfig.node.json"
+ }
+ ]
}
diff --git a/packages/create-vite/template-react-ts/tsconfig.node.json b/packages/create-vite/template-react-ts/tsconfig.node.json
index 42872c59f5b01c..3afdd6e38438be 100644
--- a/packages/create-vite/template-react-ts/tsconfig.node.json
+++ b/packages/create-vite/template-react-ts/tsconfig.node.json
@@ -1,10 +1,13 @@
{
"compilerOptions": {
"composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noEmit": true
},
"include": ["vite.config.ts"]
}
diff --git a/packages/create-vite/template-react/.eslintrc.cjs b/packages/create-vite/template-react/.eslintrc.cjs
index 4dcb43901a687f..3e212e1d4307a3 100644
--- a/packages/create-vite/template-react/.eslintrc.cjs
+++ b/packages/create-vite/template-react/.eslintrc.cjs
@@ -12,6 +12,7 @@ module.exports = {
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
+ 'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
diff --git a/packages/create-vite/template-react/package.json b/packages/create-vite/template-react/package.json
index f3fd48fea70e9d..f88081ec9e6bd8 100644
--- a/packages/create-vite/template-react/package.json
+++ b/packages/create-vite/template-react/package.json
@@ -10,17 +10,17 @@
"preview": "vite preview"
},
"dependencies": {
- "react": "^18.2.0",
- "react-dom": "^18.2.0"
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1"
},
"devDependencies": {
- "@types/react": "^18.2.33",
- "@types/react-dom": "^18.2.14",
- "@vitejs/plugin-react": "^4.1.0",
- "eslint": "^8.52.0",
- "eslint-plugin-react": "^7.33.2",
- "eslint-plugin-react-hooks": "^4.6.0",
- "eslint-plugin-react-refresh": "^0.4.4",
- "vite": "^5.0.0-beta.13"
+ "@types/react": "^18.3.3",
+ "@types/react-dom": "^18.3.0",
+ "@vitejs/plugin-react": "^4.3.1",
+ "eslint": "^8.57.0",
+ "eslint-plugin-react": "^7.34.3",
+ "eslint-plugin-react-hooks": "^4.6.2",
+ "eslint-plugin-react-refresh": "^0.4.7",
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-solid-ts/package.json b/packages/create-vite/template-solid-ts/package.json
index 17015cfa428849..6361dcf27b8ffd 100644
--- a/packages/create-vite/template-solid-ts/package.json
+++ b/packages/create-vite/template-solid-ts/package.json
@@ -5,15 +5,15 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
- "solid-js": "^1.8.4"
+ "solid-js": "^1.8.18"
},
"devDependencies": {
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13",
- "vite-plugin-solid": "^2.7.2"
+ "vite": "^5.3.2",
+ "vite-plugin-solid": "^2.10.2"
}
}
diff --git a/packages/create-vite/template-solid-ts/tsconfig.app.json b/packages/create-vite/template-solid-ts/tsconfig.app.json
new file mode 100644
index 00000000000000..348fb41806f3ff
--- /dev/null
+++ b/packages/create-vite/template-solid-ts/tsconfig.app.json
@@ -0,0 +1,28 @@
+{
+ "compilerOptions": {
+ "composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "module": "ESNext",
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/create-vite/template-solid-ts/tsconfig.json b/packages/create-vite/template-solid-ts/tsconfig.json
index 3999958409cd1d..ea9d0cd8255683 100644
--- a/packages/create-vite/template-solid-ts/tsconfig.json
+++ b/packages/create-vite/template-solid-ts/tsconfig.json
@@ -1,26 +1,11 @@
{
- "compilerOptions": {
- "target": "ES2020",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "skipLibCheck": true,
-
- /* Bundler mode */
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
- "jsx": "preserve",
- "jsxImportSource": "solid-js",
-
- /* Linting */
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- "include": ["src"],
- "references": [{ "path": "./tsconfig.node.json" }]
+ "files": [],
+ "references": [
+ {
+ "path": "./tsconfig.app.json"
+ },
+ {
+ "path": "./tsconfig.node.json"
+ }
+ ]
}
diff --git a/packages/create-vite/template-solid-ts/tsconfig.node.json b/packages/create-vite/template-solid-ts/tsconfig.node.json
index 42872c59f5b01c..3afdd6e38438be 100644
--- a/packages/create-vite/template-solid-ts/tsconfig.node.json
+++ b/packages/create-vite/template-solid-ts/tsconfig.node.json
@@ -1,10 +1,13 @@
{
"compilerOptions": {
"composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noEmit": true
},
"include": ["vite.config.ts"]
}
diff --git a/packages/create-vite/template-solid/package.json b/packages/create-vite/template-solid/package.json
index 28065b344f429a..99a0e233d95a7c 100644
--- a/packages/create-vite/template-solid/package.json
+++ b/packages/create-vite/template-solid/package.json
@@ -9,10 +9,10 @@
"preview": "vite preview"
},
"dependencies": {
- "solid-js": "^1.8.4"
+ "solid-js": "^1.8.18"
},
"devDependencies": {
- "vite": "^5.0.0-beta.13",
- "vite-plugin-solid": "^2.7.2"
+ "vite": "^5.3.2",
+ "vite-plugin-solid": "^2.10.2"
}
}
diff --git a/packages/create-vite/template-svelte-ts/package.json b/packages/create-vite/template-svelte-ts/package.json
index bd416eb20d2b9f..dfd0420910e170 100644
--- a/packages/create-vite/template-svelte-ts/package.json
+++ b/packages/create-vite/template-svelte-ts/package.json
@@ -7,15 +7,15 @@
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
- "check": "svelte-check --tsconfig ./tsconfig.json"
+ "check": "svelte-check --tsconfig ./tsconfig.json && tsc -p tsconfig.node.json"
},
"devDependencies": {
- "@sveltejs/vite-plugin-svelte": "^3.0.0-next.2",
- "@tsconfig/svelte": "^5.0.2",
- "svelte": "^4.2.2",
- "svelte-check": "^3.5.2",
- "tslib": "^2.6.2",
+ "@sveltejs/vite-plugin-svelte": "^3.1.1",
+ "@tsconfig/svelte": "^5.0.4",
+ "svelte": "^4.2.18",
+ "svelte-check": "^3.8.4",
+ "tslib": "^2.6.3",
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-svelte-ts/src/main.ts b/packages/create-vite/template-svelte-ts/src/main.ts
index 8a909a15a0ebff..4d67e2ac2af7ef 100644
--- a/packages/create-vite/template-svelte-ts/src/main.ts
+++ b/packages/create-vite/template-svelte-ts/src/main.ts
@@ -2,7 +2,7 @@ import './app.css'
import App from './App.svelte'
const app = new App({
- target: document.getElementById('app'),
+ target: document.getElementById('app')!,
})
export default app
diff --git a/packages/create-vite/template-svelte-ts/tsconfig.json b/packages/create-vite/template-svelte-ts/tsconfig.json
index 5fb548f2b4f61a..df56300cc65f66 100644
--- a/packages/create-vite/template-svelte-ts/tsconfig.json
+++ b/packages/create-vite/template-svelte-ts/tsconfig.json
@@ -13,7 +13,8 @@
*/
"allowJs": true,
"checkJs": true,
- "isolatedModules": true
+ "isolatedModules": true,
+ "moduleDetection": "force"
},
"include": ["src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
diff --git a/packages/create-vite/template-svelte-ts/tsconfig.node.json b/packages/create-vite/template-svelte-ts/tsconfig.node.json
index 494bfe0835347c..6c2d8703f35ab1 100644
--- a/packages/create-vite/template-svelte-ts/tsconfig.node.json
+++ b/packages/create-vite/template-svelte-ts/tsconfig.node.json
@@ -1,9 +1,12 @@
{
"compilerOptions": {
"composite": true,
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
- "moduleResolution": "bundler"
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noEmit": true
},
"include": ["vite.config.ts"]
}
diff --git a/packages/create-vite/template-svelte/package.json b/packages/create-vite/template-svelte/package.json
index 550db4b3eef105..230e3a5e1bd012 100644
--- a/packages/create-vite/template-svelte/package.json
+++ b/packages/create-vite/template-svelte/package.json
@@ -9,8 +9,8 @@
"preview": "vite preview"
},
"devDependencies": {
- "@sveltejs/vite-plugin-svelte": "^3.0.0-next.2",
- "svelte": "^4.2.2",
- "vite": "^5.0.0-beta.13"
+ "@sveltejs/vite-plugin-svelte": "^3.1.1",
+ "svelte": "^4.2.18",
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-vanilla-ts/package.json b/packages/create-vite/template-vanilla-ts/package.json
index e636147bd68a0f..b572532756b1bf 100644
--- a/packages/create-vite/template-vanilla-ts/package.json
+++ b/packages/create-vite/template-vanilla-ts/package.json
@@ -10,6 +10,6 @@
},
"devDependencies": {
"typescript": "^5.2.2",
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-vanilla-ts/tsconfig.json b/packages/create-vite/template-vanilla-ts/tsconfig.json
index 75abdef2659446..7bb0db29851c74 100644
--- a/packages/create-vite/template-vanilla-ts/tsconfig.json
+++ b/packages/create-vite/template-vanilla-ts/tsconfig.json
@@ -11,6 +11,7 @@
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
+ "moduleDetection": "force",
"noEmit": true,
/* Linting */
diff --git a/packages/create-vite/template-vanilla/package.json b/packages/create-vite/template-vanilla/package.json
index f7b023f0855165..985973e1444d58 100644
--- a/packages/create-vite/template-vanilla/package.json
+++ b/packages/create-vite/template-vanilla/package.json
@@ -9,6 +9,6 @@
"preview": "vite preview"
},
"devDependencies": {
- "vite": "^5.0.0-beta.13"
+ "vite": "^5.3.2"
}
}
diff --git a/packages/create-vite/template-vue-ts/.vscode/extensions.json b/packages/create-vite/template-vue-ts/.vscode/extensions.json
index c0a6e5a48110e4..a7cea0b0678120 100644
--- a/packages/create-vite/template-vue-ts/.vscode/extensions.json
+++ b/packages/create-vite/template-vue-ts/.vscode/extensions.json
@@ -1,3 +1,3 @@
{
- "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
+ "recommendations": ["Vue.volar"]
}
diff --git a/packages/create-vite/template-vue-ts/README.md b/packages/create-vite/template-vue-ts/README.md
index ef72fd52424558..33895ab2002862 100644
--- a/packages/create-vite/template-vue-ts/README.md
+++ b/packages/create-vite/template-vue-ts/README.md
@@ -2,17 +2,4 @@
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 ` asset
for (const { start, end, url } of scriptUrls) {
- if (!isExcludedUrl(url)) {
- s.update(start, end, await urlToBuiltUrl(url, id, config, this))
- } else if (checkPublicFile(url, config)) {
- s.update(start, end, toOutputPublicFilePath(url))
+ if (checkPublicFile(url, config)) {
+ s.update(
+ start,
+ end,
+ partialEncodeURIPath(toOutputPublicFilePath(url)),
+ )
+ } else if (!isExcludedUrl(url)) {
+ s.update(
+ start,
+ end,
+ partialEncodeURIPath(await urlToBuiltUrl(url, id, config, this)),
+ )
}
}
@@ -649,6 +719,12 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
attrs: {
...(isAsync ? { async: true } : {}),
type: 'module',
+ // crossorigin must be set not only for serving assets in a different origin
+ // but also to make it possible to preload the script using ``.
+ // `
+
+