diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 763dfcfc467d9d..06fe0e7ea2aaff 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -28,6 +28,7 @@ "react-router", // `react-router:v6.0.0+` has breaking changes "react-router-dom", // `react-router-dom:v6.0.0+` has breaking changes "source-map", // `source-map:v0.7.0+` needs more investigation + "dotenv-expand", // `dotenv-expand:6.0.0+` has breaking changes (#6858) // ESM Only => https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-move-my-commonjs-project-to-esm "node-fetch", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64166e7158caf3..69ba432050fa7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ concurrency: jobs: build: + timeout-minutes: 20 runs-on: ${{ matrix.os }} strategy: matrix: @@ -43,7 +44,7 @@ jobs: version: 6 - name: Set node version to ${{ matrix.node_version }} - uses: actions/setup-node@v2 + uses: actions/setup-node@v3 with: node-version: ${{ matrix.node_version }} cache: "pnpm" @@ -67,6 +68,7 @@ jobs: run: pnpm run test-build -- --runInBand lint: + timeout-minutes: 10 runs-on: ubuntu-latest name: "Lint: node-16, ubuntu-latest" steps: @@ -80,7 +82,7 @@ jobs: version: 6 - name: Set node version to 16 - uses: actions/setup-node@v2 + uses: actions/setup-node@v3 with: node-version: 16 cache: "pnpm" diff --git a/.github/workflows/issue-close-require.yml b/.github/workflows/issue-close-require.yml index 02ac374b06c426..97f9dd3a449c3c 100644 --- a/.github/workflows/issue-close-require.yml +++ b/.github/workflows/issue-close-require.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest steps: - name: need reproduction - uses: actions-cool/issues-helper@v2 + uses: actions-cool/issues-helper@v3 with: actions: "close-issues" token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml index a63021952fd73d..b6f3919dfa63a2 100644 --- a/.github/workflows/issue-labeled.yml +++ b/.github/workflows/issue-labeled.yml @@ -10,7 +10,7 @@ jobs: steps: - name: contribution welcome if: github.event.label.name == 'contribution welcome' || github.event.label.name == 'help wanted' - uses: actions-cool/issues-helper@v2 + uses: actions-cool/issues-helper@v3 with: actions: "create-comment, remove-labels" token: ${{ secrets.GITHUB_TOKEN }} @@ -21,7 +21,7 @@ jobs: - name: remove pending if: github.event.label.name == 'enhancement' || github.event.label.name == 'bug' || (contains(github.event.label.name, 'pending triage') == false && startsWith(github.event.label.name, 'bug:') == true) - uses: actions-cool/issues-helper@v2 + uses: actions-cool/issues-helper@v3 with: actions: "remove-labels" token: ${{ secrets.GITHUB_TOKEN }} @@ -30,7 +30,7 @@ jobs: - name: need reproduction if: github.event.label.name == 'need reproduction' - uses: actions-cool/issues-helper@v2 + uses: actions-cool/issues-helper@v3 with: actions: "create-comment, remove-labels" token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000000000..9e22af5aed6ee8 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,46 @@ +name: Publish Package + +on: + push: + tags: + - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10 + - "plugin-*" # Push events to matching plugin-*, i.e. plugin-(vue|vue-jsx|react|legacy)@1.0.0 + - "create-vite*" # # Push events to matching create-vite*, i.e. create-vite@1.0.0 + +jobs: + publish: + # prevents this action from running on forks + if: github.repository == 'vitejs/vite' + runs-on: ubuntu-latest + environment: Release + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Install pnpm + uses: pnpm/action-setup@v2 + with: + version: 6 + + - name: Set node version to 16.x + uses: actions/setup-node@v3 + with: + node-version: 16.x + registry-url: https://registry.npmjs.org/ + cache: "pnpm" + + - name: Install deps + run: pnpm install + + - name: Creating .npmrc + run: | + cat << EOF > "$HOME/.npmrc" + //registry.npmjs.org/:_authToken=$NPM_TOKEN + EOF + env: + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Publish package + run: pnpm run ci-publish -- ${{ github.ref_name }} + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 5ed9495899340a..f9d5b8de30bec9 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -1,4 +1,4 @@ -name: release +name: Add GitHub Release Tag on: push: diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000000000..4abbb42e5ef159 --- /dev/null +++ b/.npmrc @@ -0,0 +1,7 @@ +hoist-pattern[]=*eslint* +hoist-pattern[]=*babel* +hoist-pattern[]=*jest* +hoist-pattern[]=@emotion/* +hoist-pattern[]=postcss +hoist-pattern[]=pug +hoist-pattern[]=source-map-support diff --git a/.prettierignore b/.prettierignore index 1692b9d26cfa20..c624a3a21eecfe 100644 --- a/.prettierignore +++ b/.prettierignore @@ -10,3 +10,4 @@ pnpm-lock.yaml pnpm-workspace.yaml packages/playground/tsconfig-json-load-error/has-error/tsconfig.json packages/playground/html/invalid.html +packages/playground/worker/classic-worker.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5b8f1fed7192c3..31c1f34f3a4815 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,6 +14,36 @@ To develop and test the core `vite` package: You can alternatively use [Vite.js Docker Dev](https://github.com/nystudio107/vitejs-docker-dev) for a containerized Docker setup for Vite.js development. +## Debugging + +If you want to use break point and explore code execution you can use the ["Run and debug"](https://code.visualstudio.com/docs/editor/debugging) feature from vscode. + +1. Add a `debugger` statement where you want to stop the code execution. + +2. Click on the "Run and Debug" icon in the activity bar of the editor. + +3. Click on the "Javascript Debug Terminal" button. + +4. It will open a terminal, then go to `packages/playground/xxx` and run `pnpm run dev`. + +5. The execution will stop and you'll use the [Debug toolbar](https://code.visualstudio.com/docs/editor/debugging#_debug-actions) to continue, step over, restart the process... + +### Debugging errors in Jest tests using Playwright (Chromium) + +Some errors are masked and hidden away because of the layers of abstraction and sandboxed nature added by Jest, Playwright, and Chromium. In order to see what's actually going wrong and the contents of the devtools console in those instances, follow this setup: + +1. Add a `debugger` statement to the `scripts/jestPerTestSetup.ts` -> `afterAll` hook. This will pause execution before the tests quit and the Playwright browser instance exits. + +1. Run the tests with the `debug-serve` script command which will enable remote debugging: `pnpm run debug-serve -- --runInBand resolve`. + +1. Wait for inspector devtools to open in your browser and the debugger to attach. + +1. In the sources panel in the right column, click the play button to resume execution and allow the tests to run which will open a Chromium instance. + +1. Focusing the Chomium instance, you can open the browser devtools and inspect the console there to find the underlying problems. + +1. To close everything, just stop the test process back in your terminal. + ## Testing Vite against external packages You may wish to test your locally-modified copy of Vite against another package that is built with Vite. For pnpm, after building Vite, you can use [`pnpm.overrides`](https://pnpm.io/package_json#pnpmoverrides). Please note that `pnpm.overrides` must be specified in the root `package.json` and you must first list the package as a dependency in the root `package.json`: diff --git a/README.md b/README.md index be96a1bcf73ada..546014a12c7116 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,6 @@ In addition, Vite is highly extensible via its [Plugin API](https://vitejs.dev/g [Read the Docs to Learn More](https://vitejs.dev). -## Migrating from 1.x - -Check out the [Migration Guide](https://vitejs.dev/guide/migration.html) if you are upgrading from 1.x. - ## Packages | Package | Version (click for changelogs) | @@ -55,3 +51,11 @@ See [Contributing Guide](https://github.com/vitejs/vite/blob/main/CONTRIBUTING.m ## License MIT + +## Sponsors + +

+ + sponsors + +

diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index fc635028f95a73..ee76a29986d3fb 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -7,6 +7,9 @@ module.exports = { title: 'Vite', description: 'Next Generation Frontend Tooling', head: [['link', { rel: 'icon', type: 'image/svg+xml', href: '/logo.svg' }]], + vue: { + reactivityTransform: true + }, themeConfig: { repo: 'vitejs/vite', logo: '/logo.svg', diff --git a/docs/.vitepress/theme/SponsorsGroup.vue b/docs/.vitepress/theme/SponsorsGroup.vue new file mode 100644 index 00000000000000..691f5f5b0f1dc2 --- /dev/null +++ b/docs/.vitepress/theme/SponsorsGroup.vue @@ -0,0 +1,137 @@ + + + + + + + diff --git a/docs/.vitepress/theme/SponsorsSidebar.vue b/docs/.vitepress/theme/SponsorsSidebar.vue new file mode 100644 index 00000000000000..bb27c8b5ee157d --- /dev/null +++ b/docs/.vitepress/theme/SponsorsSidebar.vue @@ -0,0 +1,31 @@ + + + + + diff --git a/docs/.vitepress/theme/index.js b/docs/.vitepress/theme/index.js index 5d0a1b7a652039..babdc165f30ed8 100644 --- a/docs/.vitepress/theme/index.js +++ b/docs/.vitepress/theme/index.js @@ -1,7 +1,6 @@ import Theme from 'vitepress/theme' import { h } from 'vue' -import sponsors from './sponsors.json' -import './sponsors.css' +import SponsorsSidebar from './SponsorsSidebar.vue' import './custom.css' export default { @@ -9,29 +8,7 @@ export default { Layout() { return h(Theme.Layout, null, { 'sidebar-bottom': () => - h('div', { class: 'sponsors sidebar' }, [ - h( - 'a', - { - href: 'https://github.com/sponsors/yyx990803', - target: '_blank', - rel: 'noopener' - }, - [h('span', 'Sponsors')] - ), - ...sponsors.map(({ href, src, name, id }) => - h( - 'a', - { - href, - target: '_blank', - rel: 'noopener', - 'aria-label': 'sponsor-img' - }, - [h('img', { src, alt: name, id: `sponsor-${id}` })] - ) - ) - ]) + h('div', { class: 'sponsors sidebar' }, [h(SponsorsSidebar)]) }) } } diff --git a/docs/.vitepress/theme/sponsors.css b/docs/.vitepress/theme/sponsors.css deleted file mode 100644 index 904b4945ed57d6..00000000000000 --- a/docs/.vitepress/theme/sponsors.css +++ /dev/null @@ -1,56 +0,0 @@ -.sponsors { - padding: 0 1.5rem 2rem; - font-size: 0.8rem; -} - -.sponsors a { - color: #999; - margin: 1em 2em; - display: block; -} - -.sponsors img { - max-width: 160px; - max-height: 40px; -} - -.sponsors.frontpage { - text-align: center; -} - -.sponsors.frontpage img { - display: inline-block; - vertical-align: middle; -} - -.sponsors.frontpage h2 { - color: #999; - font-size: 1.2rem; - border: none; -} - -.sponsors.sidebar a img { - max-height: 36px; -} - -.platinum-sponsors { - margin-bottom: 1.5em; -} - -.platinum-sponsors a img { - max-width: 240px; - max-height: 60px; -} - -.gold-sponsors { - display: flex; - flex-wrap: wrap; - justify-content: center; - align-items: center; -} - -/* special cases */ -#sponsor-mux { - padding: 5px 0; - min-height: 36px; -} diff --git a/docs/.vitepress/theme/sponsors.json b/docs/.vitepress/theme/sponsors.json deleted file mode 100644 index 6d788ac4b84808..00000000000000 --- a/docs/.vitepress/theme/sponsors.json +++ /dev/null @@ -1,45 +0,0 @@ -[ - { - "id": "stackblitz", - "name": "StackBlitz", - "href": "https://stackblitz.com/", - "src": "/stackblitz.svg", - "tier": "platinum" - }, - { - "id": "cypress", - "name": "Cypress.io", - "href": "https://cypress.io", - "src": "/cypress.svg" - }, - { - "id": "tailwind", - "name": "Tailwind Labs", - "href": "https://tailwindcss.com", - "src": "/tailwind-labs.svg" - }, - { - "id": "vuejobs", - "name": "Vue Jobs", - "href": "https://vuejobs.com/?ref=vuejs", - "src": "/vuejobs.png" - }, - { - "id": "mux", - "name": "Mux", - "href": "https://mux.com", - "src": "/mux.svg" - }, - { - "id": "plaid", - "name": "Plaid Inc.", - "href": "https://plaid.co.jp/", - "src": "/plaid.svg" - }, - { - "id": "divriots", - "name": "divriots", - "href": "https://divriots.com/", - "src": "/divriots.png" - } -] diff --git a/docs/config/index.md b/docs/config/index.md index 233e08b8f864e3..1e824b7e431350 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -96,6 +96,22 @@ export default defineConfig(async ({ command, mode }) => { }) ``` +### Environment Variables + +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 affects the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed. + +```js +import { defineConfig, loadEnv } from 'vite' + +export default defineConfig(({ command, mode }) => { + // Load env file based on `mode` in the current working directory + const env = loadEnv(mode, process.cwd()) + return { + // build specific config + } +}) +``` + ## Shared Options ### root @@ -139,9 +155,11 @@ export default defineConfig(async ({ command, mode }) => { - Replacements are performed only when the match is surrounded by word boundaries (`\b`). + ::: warning Because it's implemented as straightforward text replacements without any syntax analysis, we recommend using `define` for CONSTANTS only. For example, `process.env.FOO` and `__APP_VERSION__` are good fits. But `process` or `global` should not be put into this option. Variables can be shimmed or polyfilled instead. + ::: ::: tip NOTE For TypeScript users, make sure to add the type declarations in the `env.d.ts` or `vite-env.d.ts` file to get type checks and Intellisense. @@ -223,6 +241,10 @@ export default defineConfig(async ({ command, mode }) => { Vite has a list of "allowed conditions" and will match the first condition that is in the allowed list. The default allowed conditions are: `import`, `module`, `browser`, `default`, and `production/development` based on current mode. The `resolve.conditions` config option allows specifying additional allowed conditions. + :::warning Resolving subpath exports + Export keys ending with "/" is deprecated by Node and may not work well. Please contact the package author to use [`*` subpath patterns](https://nodejs.org/api/packages.html#package-entry-points) instead. + ::: + ### resolve.mainFields - **Type:** `string[]` @@ -277,7 +299,7 @@ export default defineConfig(async ({ command, mode }) => { - **Type:** `string | (postcss.ProcessOptions & { plugins?: postcss.Plugin[] })` - Inline PostCSS config (expects the same format as `postcss.config.js`), or a custom path to search PostCSS config from (default is project root). The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config). + Inline PostCSS config (expects the same format as `postcss.config.js`), or a custom directory to search PostCSS config from (default is project root). The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config) and only the supported config file names are loaded. Note if an inline config is provided, Vite will not search for other PostCSS config sources. @@ -285,7 +307,7 @@ export default defineConfig(async ({ command, mode }) => { - **Type:** `Record` - Specify options to pass to CSS pre-processors. Example: + Specify options to pass to CSS pre-processors. The file extensions are used as keys for the options. Example: ```js export default defineConfig({ @@ -293,6 +315,9 @@ export default defineConfig(async ({ command, mode }) => { preprocessorOptions: { scss: { additionalData: `$injectedColor: orange;` + }, + styl: { + additionalData: `$injectedColor ?= orange` } } } @@ -499,6 +524,12 @@ export default defineConfig(async ({ command, mode }) => { Configure CORS for the dev server. This is enabled by default and allows any origin. Pass an [options object](https://github.com/expressjs/cors) to fine tune the behavior or `false` to disable. +### server.headers + +- **Type:** `OutgoingHttpHeaders` + + Specify server response headers. + ### server.force - **Type:** `boolean` @@ -508,12 +539,14 @@ export default defineConfig(async ({ command, mode }) => { ### server.hmr -- **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }` +- **Type:** `boolean | { protocol?: string, host?: string, port?: number | false, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }` Disable or configure HMR connection (in cases where the HMR websocket must use a different address from the http server). Set `server.hmr.overlay` to `false` to disable the server error overlay. + Set `server.hmr.port` to `false` when connecting to a domain without a port. + `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. Useful if you're using an SSL proxy in front of your dev server. When using `server.middlewareMode` or `server.https`, assigning `server.hmr.server` to your HTTP(S) server will process HMR connection requests through your server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port. @@ -580,6 +613,12 @@ async function createServer() { createServer() ``` +### server.base + +- **Type:** `string | undefined` + + Prepend this folder to http requests, for use when proxying vite as a subfolder. Should start and end with the `/` character. + ### server.fs.strict - **Type:** `boolean` @@ -772,19 +811,19 @@ export default defineConfig({ ### build.manifest -- **Type:** `boolean` +- **Type:** `boolean | string` - **Default:** `false` - **Related:** [Backend Integration](/guide/backend-integration) - When set to `true`, the build will also generate a `manifest.json` file that contains a mapping of non-hashed asset filenames to their hashed versions, which can then be used by a server framework to render the correct asset links. + When set to `true`, the build will also generate a `manifest.json` file that contains a mapping of non-hashed asset filenames to their hashed versions, which can then be used by a server framework to render the correct asset links. When the value is a string, it will be used as the manifest file name. ### build.ssrManifest -- **Type:** `boolean` +- **Type:** `boolean | string` - **Default:** `false` - **Related:** [Server-Side Rendering](/guide/ssr) - When set to `true`, the build will also generate a SSR manifest for determining style links and asset preload directives in production. + When set to `true`, the build will also generate a SSR manifest for determining style links and asset preload directives in production. When the value is a string, it will be used as the manifest file name. ### build.ssr @@ -923,7 +962,7 @@ export default defineConfig({ - **Type:** `string | string[]` - By default, Vite will crawl your index.html to detect dependencies that need to be pre-bundled. If build.rollupOptions.input is specified, Vite will crawl those entry points instead. + By default, Vite will crawl your `index.html` to detect dependencies that need to be pre-bundled. 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. diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md index 1651923c06cdcb..ddaa04279737f5 100644 --- a/docs/guide/api-javascript.md +++ b/docs/guide/api-javascript.md @@ -94,7 +94,7 @@ interface ViteDevServer { */ ssrLoadModule( url: string, - options?: { isolated?: boolean } + options?: { fixStacktrace?: boolean } ): Promise> /** * Fix ssr error stacktrace. diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index 01b42980197473..b3888b0fd7009b 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -458,7 +458,7 @@ In general, as long as a Rollup plugin fits the following criteria then it shoul - It doesn't use the [`moduleParsed`](https://rollupjs.org/guide/en/#moduleparsed) hook. - It doesn't have strong coupling between bundle-phase hooks and output-phase hooks. -If a Rollup plugin only makes sense for the build phase, then it can be specified under `build.rollupOptions.plugins` instead. +If a Rollup plugin only makes sense for the build phase, then it can be specified under `build.rollupOptions.plugins` instead. It will work the same as a Vite plugin with `enforce: 'post'` and `apply: 'build'`. You can also augment an existing Rollup plugin with Vite-only properties: diff --git a/docs/guide/backend-integration.md b/docs/guide/backend-integration.md index a30831e735fff7..55a4b87f1ac481 100644 --- a/docs/guide/backend-integration.md +++ b/docs/guide/backend-integration.md @@ -33,7 +33,6 @@ If you need a custom integration, you can follow the steps in this guide to conf ```html - ``` diff --git a/docs/guide/build.md b/docs/guide/build.md index aac86a237b6819..8216bcbfbac060 100644 --- a/docs/guide/build.md +++ b/docs/guide/build.md @@ -43,6 +43,20 @@ module.exports = defineConfig({ For example, you can specify multiple Rollup outputs with plugins that are only applied during build. +## Chunking Strategy + +You can configure how chunks are split using `build.rollupOptions.output.manualChunks` (see [Rollup docs](https://rollupjs.org/guide/en/#outputmanualchunks)). 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: + +```js +// vite.config.js +import { splitVendorChunkPlugin } from 'vite' +module.exports = defineConfig({ + plugins: [splitVendorChunkPlugin()] +}) +``` + +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. + ## Rebuild on files changes You can enable rollup watcher with `vite build --watch`. Or, you can directly adjust the underlying [`WatcherOptions`](https://rollupjs.org/guide/en/#watch-options) via `build.watch`: @@ -58,6 +72,8 @@ module.exports = defineConfig({ }) ``` +With the `--watch` flag enabled, changes to the `vite.config.js`, as well as any files to be bundled, will trigger a rebuild. + ## Multi-Page App Suppose you have the following source code structure: @@ -129,6 +145,15 @@ module.exports = defineConfig({ }) ``` +The entry file would contain exports that can be imported by users of your package: + +```js +// lib/main.js +import Foo from './Foo.vue' +import Bar from './Bar.vue' +export { Foo, Bar } +``` + Running `vite build` with this config uses a Rollup preset that is oriented towards shipping libraries and produces two bundle formats: `es` and `umd` (configurable via `build.lib`): ``` diff --git a/docs/guide/dep-pre-bundling.md b/docs/guide/dep-pre-bundling.md index 6864ef55899eba..0afce072e9fcc3 100644 --- a/docs/guide/dep-pre-bundling.md +++ b/docs/guide/dep-pre-bundling.md @@ -3,10 +3,10 @@ When you run `vite` for the first time, you may notice this message: ``` -Optimizable dependencies detected: -react, react-dom -Pre-bundling them to speed up dev server page load... -(this will be run only when your dependencies have changed) +Pre-bundling dependencies: + react + react-dom +(this will be run only when your dependencies or config have changed) ``` ## The Why @@ -28,6 +28,10 @@ This is Vite performing what we call "dependency pre-bundling". This process ser By pre-bundling `lodash-es` into a single module, we now only need one HTTP request instead! +::: tip NOTE +Dependency pre-bundling only applies in development mode, and uses `esbuild` to convert dependencies to ESM. In production builds, `@rollup/plugin-commonjs` is used instead. +::: + ## Automatic Dependency Discovery If an existing cache is not found, Vite will crawl your source code and automatically discover dependency imports (i.e. "bare imports" that expect to be resolved from `node_modules`) and use these found imports as entry points for the pre-bundle. The pre-bundling is performed with `esbuild` so it's typically very fast. @@ -36,11 +40,27 @@ After the server has already started, if a new dependency import is encountered ## Monorepos and Linked Dependencies -In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and instead will analyze the linked dep's dependency list instead. +In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and will analyze the linked dep's dependency list instead. + +However, this requires the linked dep to be exported as ESM. If not, you can add the dependency to [`optimizeDeps.include`](/config/#optimizedeps-include) and [`build.commonjsOptions.include`](/config/#build-commonjsoptions) in your config. + +```js +export default defineConfig({ + optimizeDeps: { + include: ['linked-dep'] + }, + build: { + commonjsOptions: { + include: [/linked-dep/, /node_modules/] + } + } +}) +``` + +When making changes to the linked dep, restart the dev server with the `--force` command line option for the changes to take effect. -::: warning Note -Linked dependencies might not work properly in the final build due to differences in dependency resolution. -Use `npm package` instead for all local dependencies to avoid issues in the final bundle. +::: warning Deduping +Due to differences in linked dependency resolution, transitive dependencies can deduplicated incorrectly, causing issues when used in runtime. If you stumble on this issue, use `npm pack` on the linked dependency to fix it. ::: ## Customizing the Behavior @@ -57,7 +77,7 @@ Both `include` and `exclude` can be used to deal with this. If the dependency is Vite caches the pre-bundled dependencies in `node_modules/.vite`. It determines whether it needs to re-run the pre-bundling step based on a few sources: -- The `dependencies` list in your `package.json` +- The `dependencies` list in your `package.json`. - Package manager lockfiles, e.g. `package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`. - Relevant fields in your `vite.config.js`, if present. diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index 1852164c4ae523..d3a6a575bce64c 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -110,4 +110,4 @@ NODE_ENV=production VITE_APP_TITLE=My App (staging) ``` -Now your staging app should have production-like behavior, but displaying a different title from production. +Now your staging app should have production-like behavior, but display a different title from production. diff --git a/docs/guide/features.md b/docs/guide/features.md index da8e3b1de092b2..7bf870646da909 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -298,10 +298,26 @@ const modules = { } ``` +`import.meta.glob` and `import.meta.globEager` also support 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' }) +``` + +The above will be transformed into the following: + +```js +// code produced by vite +const modules = { + './dir/foo.js': '{\n "msg": "foo"\n}\n', + './dir/bar.js': '{\n "msg": "bar"\n}\n' +} +``` + Note that: - This is a Vite-only feature and is not a web or ES standard. -- The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root). +- The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root) or an alias path (see [`resolve.alias` option](/config/#resolve-alias)). - The glob matching is done via `fast-glob` - check out its documentation for [supported glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax). - You should also be aware that glob imports do not accept variables, you need to directly pass the string pattern. - The glob patterns cannot contain the same quote string (i.e. `'`, `"`, `` ` ``) as outer quotes, e.g. `'/Tom\'s files/**'`, use `"/Tom's files/**"` instead. diff --git a/docs/guide/static-deploy.md b/docs/guide/static-deploy.md index 904defa37b730c..43b047dd7f53eb 100644 --- a/docs/guide/static-deploy.md +++ b/docs/guide/static-deploy.md @@ -80,6 +80,7 @@ Now the `preview` method will launch the server at `http://localhost:8080`. # echo 'www.example.com' > CNAME git init + git checkout -b main git add -A git commit -m 'deploy' @@ -164,12 +165,27 @@ You can also run the above script in your CI setup to enable automatic deploymen ## Netlify -1. On [Netlify](https://netlify.com), setup up a new project from GitHub with the following settings: +1. Install the [Netlify CLI](https://cli.netlify.com/). +2. Create a new site using `ntl init`. +3. Deploy using `ntl deploy`. - - **Build Command:** `vite build` or `npm run build` - - **Publish directory:** `dist` +```bash +# Install the Netlify CLI +$ npm install -g netlify-cli + +# Create a new site in Netlify +$ ntl init + +# Deploy to a unique preview URL +$ ntl deploy +``` -2. Hit the deploy button. +The Netlify CLI will share with you a preview URL to inspect. When you are ready to go into production, use the `prod` flag: + +```bash +# Deploy the site into production +$ ntl deploy --prod +``` ## Google Firebase diff --git a/docs/guide/why.md b/docs/guide/why.md index 59e9c138eb7dca..89ca7698394246 100644 --- a/docs/guide/why.md +++ b/docs/guide/why.md @@ -32,7 +32,7 @@ Vite improves the dev server start time by first dividing the modules in an appl When a file is edited in a bundler-based build setup, it is inefficient to rebuild the whole bundle for obvious reasons: the update speed will degrade linearly with the size of the app. -Some bundler dev server runs the bundling in memory so that it only needs to invalidate part of its module graph when a file changes, but it still needs to re-construct the entire bundle and reload the web page. Reconstructing the bundle can be expensive, and reloading the page blows away the current state of the application. This is why some bundlers support Hot Module Replacement (HMR): allowing a module to "hot replace" itself without affecting the rest of the page. This greatly improves DX - however, in practice we've found that even HMR update speed deteriorates significantly as the size of the application grows. +In some bundlers, the dev server runs the bundling in memory so that it only needs to invalidate part of its module graph when a file changes, but it still needs to re-construct the entire bundle and reload the web page. Reconstructing the bundle can be expensive, and reloading the page blows away the current state of the application. This is why some bundlers support Hot Module Replacement (HMR): allowing a module to "hot replace" itself without affecting the rest of the page. This greatly improves DX - however, in practice we've found that even HMR update speed deteriorates significantly as the size of the application grows. In Vite, HMR is performed over native ESM. When a file is edited, Vite only needs to precisely invalidate the chain between the edited module and its closest HMR boundary (most of the time only the module itself), making HMR updates consistently fast regardless of the size of your application. diff --git a/docs/index.md b/docs/index.md index 81b0eb027e8f05..ce1678de00404e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,21 +23,16 @@ features: footer: MIT Licensed | Copyright © 2019-present Evan You & Vite Contributors --- -
-

Sponsors

-
- - - -
-
- - - -
- Become a sponsor on GitHub -
- + +

Sponsors

+ + + + + +

+ Become a sponsor on GitHub +

diff --git a/docs/public/finclip.png b/docs/public/finclip.png deleted file mode 100644 index 9110e6d56c164d..00000000000000 Binary files a/docs/public/finclip.png and /dev/null differ diff --git a/package.json b/package.json index 63c7e38d0d0652..72b7076ee65d01 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,8 @@ "docs": "vitepress dev docs", "build-docs": "vitepress build docs", "serve-docs": "vitepress serve docs", + "release": "ts-node scripts/release.ts", + "ci-publish": "ts-node scripts/publishCI.ts", "build": "run-s build-vite build-plugin-vue build-plugin-react", "build-vite": "cd packages/vite && npm run build", "build-plugin-vue": "cd packages/plugin-vue && npm run build", diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json index 6ff118b7793840..5d873b83fe515b 100644 --- a/packages/create-vite/package.json +++ b/packages/create-vite/package.json @@ -12,10 +12,6 @@ "template-*" ], "main": "index.js", - "scripts": { - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . --lerna-package create-vite", - "release": "ts-node updateVersions && ts-node ../../scripts/release.ts --skipBuild" - }, "engines": { "node": ">=12.0.0" }, diff --git a/packages/create-vite/template-vue-ts/README.md b/packages/create-vite/template-vue-ts/README.md index f5342b7d8f66dd..b53dcfb1a715e6 100644 --- a/packages/create-vite/template-vue-ts/README.md +++ b/packages/create-vite/template-vue-ts/README.md @@ -8,4 +8,9 @@ This template should help get you started developing with Vue 3 and Typescript i ## Type Support For `.vue` Imports in TS -Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using manual `h(...)` calls), you can enable Volar's `.vue` type support plugin by running `Volar: Switch TS Plugin on/off` from VSCode command palette. +Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using manual `h(...)` calls), you can enable Volar's Take Over mode by following these steps: + +1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette, look for `TypeScript and JavaScript Language Features`, then right click and select `Disable (Workspace)`. By default, Take Over mode will enable itself if the default TypeScript extension is disabled. +2. Reload the VSCode window by running `Developer: Reload Window` from the command palette. + +You can learn more about Take Over mode [here](https://github.com/johnsoncodehk/volar/discussions/471). diff --git a/packages/create-vite/template-vue-ts/tsconfig.json b/packages/create-vite/template-vue-ts/tsconfig.json index af31eb8152d3cb..52205ea0029c99 100644 --- a/packages/create-vite/template-vue-ts/tsconfig.json +++ b/packages/create-vite/template-vue-ts/tsconfig.json @@ -8,6 +8,7 @@ "jsx": "preserve", "sourceMap": true, "resolveJsonModule": true, + "isolatedModules": true, "esModuleInterop": true, "lib": ["esnext", "dom"] }, diff --git a/packages/create-vite/updateVersions.ts b/packages/create-vite/updateVersions.ts deleted file mode 100644 index 7125fce9119f07..00000000000000 --- a/packages/create-vite/updateVersions.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { readdirSync, writeFileSync } from 'fs' -import { join } from 'path' - -const latestVersion = require('../vite/package.json').version -const isLatestPreRelease = /beta|alpha|rc/.test(latestVersion) - -;(async () => { - const templates = readdirSync(__dirname).filter((dir) => - dir.startsWith('template-') - ) - for (const template of templates) { - const pkgPath = join(__dirname, template, `package.json`) - const pkg = require(pkgPath) - if (!isLatestPreRelease) { - pkg.devDependencies.vite = `^` + latestVersion - } - if (template.startsWith('template-vue')) { - pkg.devDependencies['@vitejs/plugin-vue'] = - `^` + require('../plugin-vue/package.json').version - } - writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n') - } -})() diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts index c51bb4094b7b8c..0635236bd7369e 100644 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ b/packages/playground/assets/__tests__/assets.spec.ts @@ -8,7 +8,8 @@ import { readManifest, readFile, editFile, - notifyRebuildComplete + notifyRebuildComplete, + untilUpdated } from '../../testUtils' const assetMatch = isBuild @@ -37,7 +38,7 @@ describe('injected scripts', () => { test('html-proxy', async () => { const hasHtmlProxy = await page.$( - 'script[type="module"][src="/foo/index.html?html-proxy&index=0.js"]' + 'script[type="module"][src^="/foo/index.html?html-proxy"]' ) if (isBuild) { expect(hasHtmlProxy).toBeFalsy() @@ -120,6 +121,10 @@ describe('css url() references', () => { const match = isBuild ? `data:image/png;base64` : `/foo/nested/icon.png` expect(await getBg('.css-url-base64-inline')).toMatch(match) expect(await getBg('.css-url-quotes-base64-inline')).toMatch(match) + const icoMatch = isBuild ? `data:image/x-icon;base64` : `favicon.ico` + const el = await page.$(`link.ico`) + const herf = await el.getAttribute('href') + expect(herf).toMatch(icoMatch) }) test('multiple urls on the same line', async () => { @@ -228,6 +233,12 @@ test('new URL(`${dynamic}`, import.meta.url)', async () => { ) }) +test('new URL(`non-existent`, import.meta.url)', async () => { + expect(await page.textContent('.non-existent-import-meta-url')).toMatch( + '/foo/non-existent' + ) +}) + if (isBuild) { test('manifest', async () => { const manifest = readManifest('foo') @@ -254,3 +265,15 @@ describe('css and assets in css in build watch', () => { }) } }) + +if (!isBuild) { + test('@import in html style tag hmr', async () => { + await untilUpdated(() => getColor('.import-css'), 'rgb(0, 136, 255)') + editFile( + './css/import.css', + (code) => code.replace('#0088ff', '#00ff88'), + true + ) + await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)') + }) +} diff --git a/packages/playground/assets/favicon.ico b/packages/playground/assets/favicon.ico new file mode 100644 index 00000000000000..d75d248ef0b150 Binary files /dev/null and b/packages/playground/assets/favicon.ico differ diff --git a/packages/playground/assets/index.html b/packages/playground/assets/index.html index f3b9a0b372a608..25c889a445b771 100644 --- a/packages/playground/assets/index.html +++ b/packages/playground/assets/index.html @@ -2,6 +2,7 @@ + @@ -137,6 +138,14 @@

new URL('...', import.meta.url)

+

new URL('...', import.meta.url,) (with comma)

+ + + +

new URL('...', import.meta.url,) (with comma + new line)

+ + +

new URL(`./${dynamic}`, import.meta.url)

@@ -147,6 +156,21 @@

new URL(`./${dynamic}`, import.meta.url)

+

new URL(`./${dynamic}`, import.meta.url,) (with comma)

+

+ + +

+

+ + +

+ +

new URL(`non-existent`, import.meta.url)

+

+ +

+

simple script tag import-expression

diff --git a/packages/playground/env-nested/package.json b/packages/playground/env-nested/package.json new file mode 100644 index 00000000000000..8fecc69a41c2f4 --- /dev/null +++ b/packages/playground/env-nested/package.json @@ -0,0 +1,11 @@ +{ + "name": "test-env-nested", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../vite/bin/vite", + "preview": "vite preview" + } +} diff --git a/packages/playground/env-nested/vite.config.js b/packages/playground/env-nested/vite.config.js new file mode 100644 index 00000000000000..0e46100698650d --- /dev/null +++ b/packages/playground/env-nested/vite.config.js @@ -0,0 +1,5 @@ +const { defineConfig } = require('vite') + +module.exports = defineConfig({ + envDir: './envs' +}) diff --git a/packages/playground/fs-serve/root/src/index.html b/packages/playground/fs-serve/root/src/index.html index c8b294e86ab0ea..9e4f728a593a91 100644 --- a/packages/playground/fs-serve/root/src/index.html +++ b/packages/playground/fs-serve/root/src/index.html @@ -8,6 +8,10 @@

Safe Fetch


 

 
+

Safe Fetch Subdirectory

+

+

+
 

Unsafe Fetch


 

@@ -42,6 +46,15 @@ 

Denied

.then((data) => { text('.safe-fetch', JSON.stringify(data)) }) + // inside allowed dir, safe fetch + fetch('/src/subdir/safe.txt') + .then((r) => { + text('.safe-fetch-subdir-status', r.status) + return r.text() + }) + .then((data) => { + text('.safe-fetch-subdir', JSON.stringify(data)) + }) // outside of allowed dir, treated as unsafe fetch('/unsafe.txt') diff --git a/packages/playground/fs-serve/root/src/subdir/safe.txt b/packages/playground/fs-serve/root/src/subdir/safe.txt new file mode 100644 index 00000000000000..3f3d0607101642 --- /dev/null +++ b/packages/playground/fs-serve/root/src/subdir/safe.txt @@ -0,0 +1 @@ +KEY=safe diff --git a/packages/playground/glob-import/__tests__/glob-import.spec.ts b/packages/playground/glob-import/__tests__/glob-import.spec.ts index 3a2425736548ea..fff8d9fe202ebc 100644 --- a/packages/playground/glob-import/__tests__/glob-import.spec.ts +++ b/packages/playground/glob-import/__tests__/glob-import.spec.ts @@ -7,6 +7,9 @@ import { } from '../../testUtils' const filteredResult = { + './alias.js': { + default: 'hi' + }, './foo.js': { msg: 'foo' } @@ -30,11 +33,19 @@ const json = isBuild const allResult = { // JSON file should be properly transformed + '/dir/alias.js': { + default: 'hi' + }, '/dir/baz.json': json, '/dir/foo.js': { msg: 'foo' }, '/dir/index.js': { + globWithAlias: { + './alias.js': { + default: 'hi' + } + }, modules: filteredResult }, '/dir/nested/bar.js': { @@ -80,6 +91,7 @@ if (!isBuild) { '/dir/a.js': {}, ...allResult, '/dir/index.js': { + ...allResult['/dir/index.js'], modules: { './a.js': {}, ...allResult['/dir/index.js'].modules @@ -102,6 +114,7 @@ if (!isBuild) { }, ...allResult, '/dir/index.js': { + ...allResult['/dir/index.js'], modules: { './a.js': { msg: 'a' diff --git a/packages/playground/glob-import/dir/alias.js b/packages/playground/glob-import/dir/alias.js new file mode 100644 index 00000000000000..9c533d93b9a98a --- /dev/null +++ b/packages/playground/glob-import/dir/alias.js @@ -0,0 +1 @@ +export default 'hi' diff --git a/packages/playground/glob-import/dir/index.js b/packages/playground/glob-import/dir/index.js index d13d470e2b2b80..fb87f69f0f3a61 100644 --- a/packages/playground/glob-import/dir/index.js +++ b/packages/playground/glob-import/dir/index.js @@ -1,3 +1,4 @@ const modules = import.meta.globEager('./*.(js|ts)') +const globWithAlias = import.meta.globEager('@dir/al*.js') -export { modules } +export { modules, globWithAlias } diff --git a/packages/playground/glob-import/index.html b/packages/playground/glob-import/index.html index bb5e2f3c18f752..52d41b817a169c 100644 --- a/packages/playground/glob-import/index.html +++ b/packages/playground/glob-import/index.html @@ -40,7 +40,7 @@ + + + + diff --git a/packages/playground/optimize-deps/package.json b/packages/playground/optimize-deps/package.json index 0606343e0dce3c..09c578d684ffe7 100644 --- a/packages/playground/optimize-deps/package.json +++ b/packages/playground/optimize-deps/package.json @@ -17,12 +17,14 @@ "dep-esbuild-plugin-transform": "file:./dep-esbuild-plugin-transform", "dep-linked": "link:./dep-linked", "dep-linked-include": "link:./dep-linked-include", + "dep-not-js": "file:./dep-not-js", "lodash-es": "^4.17.21", "nested-exclude": "file:./nested-exclude", "phoenix": "^1.6.2", "react": "^17.0.2", "react-dom": "^17.0.2", "resolve-linked": "workspace:0.0.0", + "url": "^0.11.0", "vue": "^3.2.25", "vuex": "^4.0.0" }, diff --git a/packages/playground/optimize-deps/vite.config.js b/packages/playground/optimize-deps/vite.config.js index 45a50aaf85ede6..a989cf1961de11 100644 --- a/packages/playground/optimize-deps/vite.config.js +++ b/packages/playground/optimize-deps/vite.config.js @@ -1,3 +1,4 @@ +const fs = require('fs') const vue = require('@vitejs/plugin-vue') /** @@ -5,7 +6,10 @@ const vue = require('@vitejs/plugin-vue') */ module.exports = { resolve: { - dedupe: ['react'] + dedupe: ['react'], + alias: { + 'node:url': 'url' + } }, optimizeDeps: { @@ -36,6 +40,7 @@ module.exports = { plugins: [ vue(), + notjs(), // for axios request test { name: 'mock', @@ -48,3 +53,39 @@ module.exports = { } ] } + +// Handles .notjs file, basically remove wrapping and tags +function notjs() { + return { + name: 'notjs', + config() { + return { + optimizeDeps: { + extensions: ['.notjs'], + esbuildOptions: { + plugins: [ + { + name: 'esbuild-notjs', + setup(build) { + build.onLoad({ filter: /\.notjs$/ }, ({ path }) => { + let contents = fs.readFileSync(path, 'utf-8') + contents = contents + .replace('', '') + .replace('', '') + return { contents, loader: 'js' } + }) + } + } + ] + } + } + } + }, + transform(code, id) { + if (id.endsWith('.notjs')) { + code = code.replace('', '').replace('', '') + return { code } + } + } + } +} diff --git a/packages/playground/resolve/__tests__/resolve.spec.ts b/packages/playground/resolve/__tests__/resolve.spec.ts index 97e4a5dd0add7b..b64da138033fc0 100644 --- a/packages/playground/resolve/__tests__/resolve.spec.ts +++ b/packages/playground/resolve/__tests__/resolve.spec.ts @@ -16,6 +16,10 @@ test('deep import with exports field', async () => { expect(await page.textContent('.exports-deep')).toMatch('[success]') }) +test('deep import with query with exports field', async () => { + expect(await page.textContent('.exports-deep-query')).not.toMatch('fail') +}) + test('deep import with exports field + exposed dir', async () => { expect(await page.textContent('.exports-deep-exposed-dir')).toMatch( '[success]' diff --git a/packages/playground/resolve/exports-path/deep.json b/packages/playground/resolve/exports-path/deep.json new file mode 100644 index 00000000000000..97e19265d6c843 --- /dev/null +++ b/packages/playground/resolve/exports-path/deep.json @@ -0,0 +1,3 @@ +{ + "foo": "json" +} diff --git a/packages/playground/resolve/exports-path/package.json b/packages/playground/resolve/exports-path/package.json index 045fc85db128d2..7355da2f63f616 100644 --- a/packages/playground/resolve/exports-path/package.json +++ b/packages/playground/resolve/exports-path/package.json @@ -8,6 +8,7 @@ "require": "./cjs.js" }, "./deep.js": "./deep.js", + "./deep.json": "./deep.json", "./dir/": "./dir/", "./dir-mapped/*": { "import": "./dir/*", diff --git a/packages/playground/resolve/index.html b/packages/playground/resolve/index.html index db0a4bc54f1ad7..c0569345d86837 100644 --- a/packages/playground/resolve/index.html +++ b/packages/playground/resolve/index.html @@ -12,6 +12,9 @@

Entry resolving with exports field

Deep import with exports field

fail

+

Deep import with query with exports field

+

fail

+

Deep import with exports field + exposed directory

fail

@@ -38,6 +41,17 @@

fail

+

+ A ts module can import another tsx module using its corresponding jsx file + name +

+

fail

+ +

+ A ts module can import another tsx module using its corresponding js file name +

+

fail

+

Resolve file name containing dot

fail

@@ -100,6 +114,10 @@

resolve package that contains # in path

import { msg as deepMsg } from 'resolve-exports-path/deep.js' text('.exports-deep', deepMsg) + // deep import w/ exports w/ query + import deepPath from 'resolve-exports-path/deep.json?url' + text('.exports-deep-query', deepPath) + // deep import w/ exposed dir import { msg as exposedDirMsg } from 'resolve-exports-path/dir/dir' text('.exports-deep-exposed-dir', exposedDirMsg) @@ -130,6 +148,12 @@

resolve package that contains # in path

import { msg as tsExtensionMsg } from './ts-extension' text('.ts-extension', tsExtensionMsg) + import { msgJsx as tsJsxExtensionMsg } from './ts-extension' + text('.jsx-extension', tsJsxExtensionMsg) + + import { msgTsx as tsTsxExtensionMsg } from './ts-extension' + text('.tsx-extension', tsTsxExtensionMsg) + // filename with dot import { bar } from './util/bar.util' text('.dot', bar()) diff --git a/packages/playground/resolve/ts-extension/hellojsx.tsx b/packages/playground/resolve/ts-extension/hellojsx.tsx new file mode 100644 index 00000000000000..a8f610b399b17a --- /dev/null +++ b/packages/playground/resolve/ts-extension/hellojsx.tsx @@ -0,0 +1 @@ +export const msgJsx = '[success] use .jsx extension to import a tsx module' diff --git a/packages/playground/resolve/ts-extension/hellotsx.tsx b/packages/playground/resolve/ts-extension/hellotsx.tsx new file mode 100644 index 00000000000000..b7461ca71ded6c --- /dev/null +++ b/packages/playground/resolve/ts-extension/hellotsx.tsx @@ -0,0 +1 @@ +export const msgTsx = '[success] use .js extension to import a tsx module' diff --git a/packages/playground/resolve/ts-extension/index.ts b/packages/playground/resolve/ts-extension/index.ts index e095619ee4d716..bdb326f8778e64 100644 --- a/packages/playground/resolve/ts-extension/index.ts +++ b/packages/playground/resolve/ts-extension/index.ts @@ -1,3 +1,5 @@ import { msg } from './hello.js' +import { msgJsx } from './hellojsx.jsx' +import { msgTsx } from './hellotsx.js' -export { msg } +export { msg, msgJsx, msgTsx } diff --git a/packages/playground/tailwind/__test__/tailwind.spec.ts b/packages/playground/tailwind/__test__/tailwind.spec.ts index 105eb245bf207e..47f6b7ccf49037 100644 --- a/packages/playground/tailwind/__test__/tailwind.spec.ts +++ b/packages/playground/tailwind/__test__/tailwind.spec.ts @@ -5,7 +5,7 @@ test('should render', async () => { }) if (!isBuild) { - test('regenerate CSS and HMR', async () => { + test('regenerate CSS and HMR (glob pattern)', async () => { browserLogs.length = 0 const el = await page.$('#pagetitle') const el2 = await page.$('#helloroot') @@ -37,4 +37,24 @@ if (!isBuild) { browserLogs.length = 0 }) + + test('regenerate CSS and HMR (relative path)', async () => { + browserLogs.length = 0 + const el = await page.$('h1') + + expect(await getColor(el)).toBe('black') + + editFile('src/App.vue', (code) => + code.replace('text-black', 'text-[rgb(11,22,33)]') + ) + + await untilUpdated(() => getColor(el), 'rgb(11, 22, 33)') + + expect(browserLogs).toMatchObject([ + '[vite] css hot updated: /index.css', + '[vite] hot updated: /src/App.vue' + ]) + + browserLogs.length = 0 + }) } diff --git a/packages/playground/tailwind/src/App.vue b/packages/playground/tailwind/src/App.vue index b032d5e0db77e3..25835fc414a06f 100644 --- a/packages/playground/tailwind/src/App.vue +++ b/packages/playground/tailwind/src/App.vue @@ -1,6 +1,6 @@