diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 48a0bd7773b0d7..9f6bf0deb86303 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -8,6 +8,7 @@ module.exports = defineConfig({ 'plugin:node/recommended', 'plugin:@typescript-eslint/recommended' ], + plugins: ['import'], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', @@ -29,14 +30,7 @@ module.exports = defineConfig({ 'node/no-missing-import': [ 'error', { - allowModules: [ - 'types', - 'estree', - 'testUtils', - 'less', - 'sass', - 'stylus' - ], + allowModules: ['types', 'estree', 'less', 'sass', 'stylus'], tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'] } ], @@ -63,7 +57,7 @@ module.exports = defineConfig({ 'node/no-extraneous-import': [ 'error', { - allowModules: ['vite', 'less', 'sass'] + allowModules: ['vite', 'less', 'sass', 'vitest'] } ], 'node/no-extraneous-require': [ @@ -93,6 +87,18 @@ module.exports = defineConfig({ '@typescript-eslint/consistent-type-imports': [ 'error', { prefer: 'type-imports' } + ], + + 'import/order': 'error', + 'sort-imports': [ + 'error', + { + ignoreCase: false, + ignoreDeclarationSort: true, + ignoreMemberSort: false, + memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], + allowSeparatedGroups: false + } ] }, overrides: [ @@ -103,16 +109,18 @@ module.exports = defineConfig({ } }, { - files: ['packages/vite/types/**'], + files: ['packages/vite/types/**', '*.spec.ts'], rules: { 'node/no-extraneous-import': 'off' } }, { - files: ['packages/playground/**'], + files: ['playground/**'], rules: { 'node/no-extraneous-import': 'off', - 'node/no-extraneous-require': 'off' + 'node/no-extraneous-require': 'off', + 'node/no-missing-import': 'off', + 'node/no-missing-require': 'off' } }, { diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 06fe0e7ea2aaff..17898db2741284 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -1,11 +1,7 @@ { "extends": ["config:base", "schedule:weekly", "group:allNonMajor"], "labels": ["dependencies"], - "ignorePaths": [ - "packages/playground/**", - "packages/create-vite/template-*/**", - "**/__tests__/**" - ], + "ignorePaths": ["**/__tests__/**"], "pin": false, "rangeStrategy": "bump", "node": false, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2832dab118e279..05813fbd73e244 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,8 @@ on: - feat/* - fix/* - perf/* + - v1 + - v2 pull_request: workflow_dispatch: @@ -27,7 +29,7 @@ jobs: strategy: matrix: os: [ubuntu-latest] - node_version: [12, 14, 16, 17, 18] + node_version: [14, 16, 18] include: - os: macos-latest node_version: 16 @@ -40,6 +42,10 @@ jobs: # node_version: 18 fail-fast: false + env: + # Install playwright's binray under node_modules so it will be cached together + PLAYWRIGHT_BROWSERS_PATH: "0" + name: "Build&Test: node-${{ matrix.node_version }}, ${{ matrix.os }}" steps: - name: Checkout @@ -47,8 +53,6 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v2 - with: - version: 6 - name: Set node version to ${{ matrix.node_version }} uses: actions/setup-node@v3 @@ -59,6 +63,9 @@ jobs: - name: Install deps run: pnpm install + - name: Install Playwright + run: pnpm playwright install + - name: Build vite run: pnpm run ci-build-vite @@ -68,11 +75,14 @@ jobs: - name: Build plugin-react run: pnpm run build-plugin-react + - name: Test unit + run: pnpm run test-unit + - name: Test serve - run: pnpm run test-serve -- --runInBand + run: pnpm run test-serve - name: Test build - run: pnpm run test-build -- --runInBand + run: pnpm run test-build lint: timeout-minutes: 10 @@ -85,8 +95,6 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v2 - with: - version: 6 - name: Set node version to 16 uses: actions/setup-node@v3 @@ -96,14 +104,20 @@ jobs: - name: Install deps run: pnpm install + env: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" - name: Prepare run: | pnpm run ci-build-vite pnpm run build-plugin-vue + pnpm run build-plugin-react - name: Lint run: pnpm run lint - name: Check formatting run: pnpm prettier --check . + + - name: Typecheck + run: pnpm run typecheck diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c58c28adac7b40..022a0cbc77e7fc 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -31,14 +31,8 @@ jobs: - 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 }} + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" - name: Publish package run: pnpm run ci-publish -- ${{ github.ref_name }} diff --git a/.gitignore b/.gitignore index 44abdd7bf563db..9194d44b544c4e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,15 @@ -.DS_Store -node_modules !**/glob-import/dir/node_modules -dist -dist-ssr -TODOs.md -*.log -temp -explorations +.DS_Store .idea -*.local -/packages/vite/LICENSE *.cpuprofile +*.local +*.log /.vscode/ +/packages/vite/LICENSE +dist +dist-ssr +explorations +node_modules +playground-temp +temp +TODOs.md diff --git a/.npmrc b/.npmrc index 4abbb42e5ef159..0a8182ea5f2c53 100644 --- a/.npmrc +++ b/.npmrc @@ -1,6 +1,5 @@ hoist-pattern[]=*eslint* hoist-pattern[]=*babel* -hoist-pattern[]=*jest* hoist-pattern[]=@emotion/* hoist-pattern[]=postcss hoist-pattern[]=pug diff --git a/.prettierignore b/.prettierignore index c624a3a21eecfe..a2c1f98cf5cc02 100644 --- a/.prettierignore +++ b/.prettierignore @@ -4,10 +4,11 @@ packages/vite/temp/ packages/plugin-react/dist/ packages/plugin-vue/dist/ packages/*/CHANGELOG.md +playground-temp/ LICENSE.md .prettierignore 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 +playground/tsconfig-json-load-error/has-error/tsconfig.json +playground/html/invalid.html +playground/worker/classic-worker.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7020c97a84c80..e489730c907f44 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,8 @@ 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. +> Vite uses pnpm v7. If you are working on multiple projects with different versions of pnpm, it's recommend to enable [Corepack](https://github.com/nodejs/corepack) by running `corepack enable`. + ## 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. @@ -26,23 +28,23 @@ If you want to use break point and explore code execution you can use the ["Run 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`. +4. It will open a terminal, then go to `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) +### Debugging errors in Vitest 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: +Some errors are masked and hidden away because of the layers of abstraction and sandboxed nature added by Vitest, 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. Add a `debugger` statement to the `playground/vitestSetup.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. Run the tests with the `debug-serve` script command which will enable remote debugging: `pnpm run debug-serve 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. Focusing the Chromium 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. @@ -67,46 +69,58 @@ And re-run `pnpm install` to link the package. ## Running Tests -Each package under `packages/playground/` contains a `__tests__` directory. The tests are run using [Jest](https://jestjs.io/) + [Playwright](https://playwright.dev/) with custom integrations to make writing tests simple. The detailed setup is inside `jest.config.js` and `scripts/jest*` files. +### Integration Tests + +Each package under `playground/` contains a `__tests__` directory. The tests are run using [Vitest](https://vitest.dev/) + [Playwright](https://playwright.dev/) with custom integrations to make writing tests simple. The detailed setup is inside `vitest.config.e2e.js` and `playground/vitest*` files. -Before running the tests, make sure that [Vite has been built](#repo-setup). On Windows, you may want to [activate Developer Mode](https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development) to solve [issues with symlink creation for non-admins](https://github.com/vitejs/vite/issues/7390). +Before running the tests, make sure that [Vite has been built](#repo-setup). On Windows, you may want to [activate Developer Mode](https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development) to solve [issues with symlink creation for non-admins](https://github.com/vitejs/vite/issues/7390). Also you may want to [set git `core.symlinks` to `true` to solve issues with symlinks in git](https://github.com/vitejs/vite/issues/5242). -Each test can be run under either dev server mode or build mode. +Each integration test can be run under either dev server mode or build mode. -- `pnpm test` by default runs every test in both serve and build mode. +- `pnpm test` by default runs every integration test in both serve and build mode, and also unit tests. -- `pnpm run test-serve` runs tests only under serve mode. This is just calling `jest` so you can pass any Jest flags to this command. Since Jest will attempt to run tests in parallel, if your machine has many cores this may cause flaky test failures with multiple Playwright instances running at the same time. You can force the tests to run in series with `pnpm run test-serve -- --runInBand`. +- `pnpm run test-serve` runs tests only under serve mode. - `pnpm run test-build` runs tests only under build mode. -- You can also use `pnpm run test-serve -- [match]` or `pnpm run test-build -- [match]` to run tests in a specific playground package, e.g. `pnpm run test-serve -- asset` will run tests for both `playground/asset` and `vite/src/node/__tests__/asset` under serve mode and `vite/src/node/__tests__/**/*` just run in serve mode. +- You can also use `pnpm run test-serve [match]` or `pnpm run test-build [match]` to run tests in a specific playground package, e.g. `pnpm run test-serve asset` will run tests for both `playground/asset` and `vite/src/node/__tests__/asset` under serve mode and `vite/src/node/__tests__/**/*` just run in serve mode. Note package matching is not available for the `pnpm test` script, which always runs all tests. +### Unit Tests + +Other than tests under `playground/` for integration tests, packages might contains unit tests under their `__tests__` directory. Unit tests are powered by [Vitest](https://vitest.dev/). The detailed config is inside `vitest.config.ts` files. + +- `pnpm run test-unit` runs unit tests under each package. + +- You can also use `pnpm run test-unit [match]` to run related tests. + ### Test Env and Helpers -Inside playground tests, a global `page` object is automatically available, which is a Playwright [`Page`](https://playwright.dev/docs/api/class-page) instance that has already navigated to the served page of the current playground. So writing a test is as simple as: +Inside playground tests, you can import the `page` object from `~utils`, which is a Playwright [`Page`](https://playwright.dev/docs/api/class-page) instance that has already navigated to the served page of the current playground. So writing a test is as simple as: ```js +import { page } from '~utils' + test('should work', async () => { expect(await page.textContent('.foo')).toMatch('foo') }) ``` -Some common test helpers, e.g. `testDir`, `isBuild` or `editFile` are available in `packages/playground/testUtils.ts`. +Some common test helpers, e.g. `testDir`, `isBuild` or `editFile` are also available in the utils. Source code is located at `playground/test-utils.ts`. -Note: The test build environment uses a [different default set of Vite config](https://github.com/vitejs/vite/blob/9c6501d9c363eaa3c1e7708d531fb2a92b633db6/scripts/jestPerTestSetup.ts#L102-L122) to skip transpilation during tests to make it faster. This may produce a different result compared to the default production build. +Note: The test build environment uses a [different default set of Vite config](https://github.com/vitejs/vite/blob/main/playground/vitestSetup.ts#L102-L122) to skip transpilation during tests to make it faster. This may produce a different result compared to the default production build. ### Extending the Test Suite -To add new tests, you should find a related playground to the fix or feature (or create a new one). As an example, static assets loading are tested in the [assets playground](https://github.com/vitejs/vite/tree/main/packages/playground/assets). In this Vite App, there is a test for `?raw` imports, with [a section is defined in the `index.html` for it](https://github.com/vitejs/vite/blob/71215533ac60e8ff566dc3467feabfc2c71a01e2/packages/playground/assets/index.html#L121): +To add new tests, you should find a related playground to the fix or feature (or create a new one). As an example, static assets loading are tested in the [assets playground](https://github.com/vitejs/vite/tree/main/playground/assets). In this Vite App, there is a test for `?raw` imports, with [a section is defined in the `index.html` for it](https://github.com/vitejs/vite/blob/main/playground/assets/index.html#L121): ```html

?raw import

``` -This will be modified [with the result of a file import](https://github.com/vitejs/vite/blob/71215533ac60e8ff566dc3467feabfc2c71a01e2/packages/playground/assets/index.html#L151): +This will be modified [with the result of a file import](https://github.com/vitejs/vite/blob/main/playground/assets/index.html#L151): ```js import rawSvg from './nested/fragment.svg?raw' @@ -121,7 +135,7 @@ function text(el, text) { } ``` -In the [spec tests](https://github.com/vitejs/vite/blob/71215533ac60e8ff566dc3467feabfc2c71a01e2/packages/playground/assets/__tests__/assets.spec.ts#L180), the modifications to the DOM listed above are used to test this feature: +In the [spec tests](https://github.com/vitejs/vite/blob/main/playground/assets/__tests__/assets.spec.ts#L180), the modifications to the DOM listed above are used to test this feature: ```js test('?raw import', async () => { @@ -138,7 +152,7 @@ To work around this, playground packages that uses the `file:` protocol should a ```jsonc "scripts": { //... - "postinstall": "ts-node ../../../scripts/patchFileDeps.ts" + "postinstall": "ts-node ../../scripts/patchFileDeps.ts" } ``` diff --git a/README.md b/README.md index 546014a12c7116..a6f13829f2635f 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ In addition, Vite is highly extensible via its [Plugin API](https://vitejs.dev/g ## Packages +> This branch is for the upcoming v3.0, if you are looking for current stable releases, check the [`v2` branch](https://github.com/vitejs/vite/tree/v2) instead. + | Package | Version (click for changelogs) | | ------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- | | [vite](packages/vite) | [![vite version](https://img.shields.io/npm/v/vite.svg?label=%20)](packages/vite/CHANGELOG.md) | diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.ts similarity index 94% rename from docs/.vitepress/config.js rename to docs/.vitepress/config.ts index ee76a29986d3fb..4659ea5ab7ae4f 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.ts @@ -1,9 +1,6 @@ -// @ts-check +import { defineConfig } from 'vitepress' -/** - * @type {import('vitepress').UserConfig} - */ -module.exports = { +export default defineConfig({ title: 'Vite', description: 'Next Generation Frontend Tooling', head: [['link', { rel: 'icon', type: 'image/svg+xml', href: '/logo.svg' }]], @@ -64,6 +61,15 @@ module.exports = { } ] }, + { + text: 'v3 (next)', + items: [ + { + text: 'v2.x (stable)', + link: 'https://v2.vitejs.dev' + } + ] + }, { text: 'Languages', items: [ @@ -169,4 +175,4 @@ module.exports = { ] } } -} +}) diff --git a/docs/config/index.md b/docs/config/index.md index bab7df7a144987..8fc772f345e0ea 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -28,12 +28,14 @@ vite --config my-config.js ``` ::: tip NOTE -Vite will replace `__filename`, `__dirname`, and `import.meta.url` in config files and its deps. Using these as variable names will result in an error: +Vite will replace `__filename`, `__dirname`, and `import.meta.url` in config files and its deps. Using these as variable names or passing as a parameter to a function with string double quote (example `console.log`) will result in an error: ```js const __filename = "value" // will be transformed to const "path/vite.config.js" = "value" + +console.log("import.meta.url") // break error on build ``` ::: @@ -94,7 +96,7 @@ If the config needs to call async function, it can export a async function inste export default defineConfig(async ({ command, mode }) => { const data = await asyncFunction() return { - // build specific config + // vite config } }) ``` @@ -109,10 +111,14 @@ Note that Vite doesn't load `.env` files by default as the files to load can onl 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()) + // Load env file based on `mode` in the current working directory. + // Set the third parameter to '' to load all env regardless of the `VITE_` prefix. + const env = loadEnv(mode, process.cwd(), '') return { - // build specific config + // vite config + define: { + __APP_ENV__: env.APP_ENV + } } }) ``` @@ -160,7 +166,7 @@ export default defineConfig(({ command, mode }) => { - To be consistent with [esbuild behavior](https://esbuild.github.io/api/#define), expressions must either be a JSON object (null, boolean, number, string, array, or object) or a single identifier. - - Replacements are performed only when the match is surrounded by word boundaries (`\b`). + - Replacements are performed only when the match isn't surrounded by other letters, numbers, `_` or `$`. ::: warning Because it's implemented as straightforward text replacements without any syntax analysis, we recommend using `define` for CONSTANTS only. @@ -180,6 +186,20 @@ export default defineConfig(({ command, mode }) => { ::: + ::: tip NOTE + Since dev and build implement `define` differently, we should avoid some use cases to avoid inconsistency. + + Example: + + ```js + const obj = { + __NAME__, // Don't define object shorthand property names + __KEY__: value // Don't define object key + } + ``` + + ::: + ### plugins - **Type:** `(Plugin | Plugin[])[]` @@ -237,7 +257,7 @@ export default defineConfig(({ command, mode }) => { { "exports": { ".": { - "import": "./index.esm.js", + "import": "./index.esm.mjs", "require": "./index.cjs.js" } } @@ -499,6 +519,8 @@ export default defineConfig(({ command, mode }) => { Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options). + 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. + **Example:** ```js @@ -706,7 +728,7 @@ Defines the origin of the generated asset URLs during development. ```js export default defineConfig({ server: { - origin: 'http://127.0.0.1:8080/' + origin: 'http://127.0.0.1:8080' } }) ``` @@ -1018,7 +1040,6 @@ export default defineConfig({ - `external` is also omitted, use Vite's `optimizeDeps.exclude` option - `plugins` are merged with Vite's dep plugin - - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames` ## SSR Options diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index 50353765261e34..76b9984a069828 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -305,6 +305,28 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo Note `configureServer` is not called when running the production build so your other hooks need to guard against its absence. +### `configurePreviewServer` + +- **Type:** `(server: { middlewares: Connect.Server, httpServer: http.Server }) => (() => void) | void | Promise<(() => void) | void>` +- **Kind:** `async`, `sequential` + + Same as [`configureServer`](/guide/api-plugin.html#configureserver) but for the preview server. It provides the [connect](https://github.com/senchalabs/connect) server and its underlying [http server](https://nodejs.org/api/http.html). Similarly to `configureServer`, the `configurePreviewServer` hook is called before other middlewares are installed. If you want to inject a middleware **after** other middlewares, you can return a function from `configurePreviewServer`, which will be called after internal middlewares are installed: + + ```js + const myPlugin = () => ({ + name: 'configure-preview-server', + configurePreviewServer(server) { + // return a post hook that is called after other middlewares are + // installed + return () => { + server.middlewares.use((req, res, next) => { + // custom handle request... + }) + } + } + }) + ``` + ### `transformIndexHtml` - **Type:** `IndexHtmlTransformHook | { enforce?: 'pre' | 'post', transform: IndexHtmlTransformHook }` diff --git a/docs/guide/backend-integration.md b/docs/guide/backend-integration.md index 55a4b87f1ac481..17387bb7819ec0 100644 --- a/docs/guide/backend-integration.md +++ b/docs/guide/backend-integration.md @@ -36,7 +36,12 @@ If you need a custom integration, you can follow the steps in this guide to conf ``` - Also make sure the server is configured to serve static assets in the Vite working directory, otherwise assets such as images won't be loaded properly. + In order to properly serve assets, you have two options: + + - Make sure the server is configured to proxy static assets requests to the Vite server + - Set [`server.origin`](https://vitejs.dev/config/#server-origin) so that generated asset URLs will be resolved using the back-end server URL instead of a relative path + + This is needed for assets such as images to load properly. Note if you are using React with `@vitejs/plugin-react`, you'll also need to add this before the above scripts, since the plugin is not able to modify the HTML you are serving: diff --git a/docs/guide/build.md b/docs/guide/build.md index 8216bcbfbac060..358745d02f2cf1 100644 --- a/docs/guide/build.md +++ b/docs/guide/build.md @@ -127,7 +127,8 @@ module.exports = defineConfig({ lib: { entry: path.resolve(__dirname, 'lib/main.js'), name: 'MyLib', - fileName: (format) => `my-lib.${format}.js` + // the proper extensions will be added + fileName: 'my-lib' }, rollupOptions: { // make sure to externalize deps that shouldn't be bundled @@ -159,7 +160,7 @@ Running `vite build` with this config uses a Rollup preset that is oriented towa ``` $ vite build building for production... -[write] my-lib.es.js 0.08kb, brotli: 0.07kb +[write] my-lib.es.mjs 0.08kb, brotli: 0.07kb [write] my-lib.umd.js 0.30kb, brotli: 0.16kb ``` @@ -170,10 +171,10 @@ Recommended `package.json` for your lib: "name": "my-lib", "files": ["dist"], "main": "./dist/my-lib.umd.js", - "module": "./dist/my-lib.es.js", + "module": "./dist/my-lib.es.mjs", "exports": { ".": { - "import": "./dist/my-lib.es.js", + "import": "./dist/my-lib.es.mjs", "require": "./dist/my-lib.umd.js" } } diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index b2b1264e85a8e4..d5f45ea1158808 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -81,6 +81,14 @@ 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`. + +```json +{ + "lib": ["WebWorker"] +} +``` + ## Modes By default, the dev server (`dev` command) runs in `development` mode and the `build` command run in `production` mode. diff --git a/docs/guide/features.md b/docs/guide/features.md index 1a8c03bbd0be22..01798ad0d4ea56 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -282,10 +282,10 @@ 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 use `import.meta.globEager` instead: +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 -const modules = import.meta.globEager('./dir/*.js') +const modules = import.meta.glob('./dir/*.js', { eager: true }) ``` The above will be transformed into the following: @@ -300,7 +300,9 @@ 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: +### 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' }) @@ -311,18 +313,115 @@ 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' + './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 +const modules = import.meta.glob(['./dir/*.js', './another/*.js']) +``` + +### Negative Patterns + +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 +const modules = import.meta.glob(['./dir/*.js', '!**/bar.js']) +``` + +```js +// code produced by vite +const modules = { + './dir/foo.js': () => import('./dir/foo.js') +} +``` + +#### Named Imports + +It's possible to only import parts of the modules with the `import` options. + +```ts +const modules = import.meta.glob('./dir/*.js', { import: 'setup' }) +``` + +```ts +// code produced by vite +const modules = { + './dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup), + './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup) +} +``` + +When combined with `eager` it's even possible to have tree-shaking enabled for those modules. + +```ts +const modules = import.meta.glob('./dir/*.js', { import: 'setup', eager: true }) +``` + +```ts +// code produced by vite: +import { setup as __glob__0_0 } from './dir/foo.js' +import { setup as __glob__0_1 } from './dir/bar.js' +const modules = { + './dir/foo.js': __glob__0_0, + './dir/bar.js': __glob__0_1 +} +``` + +Set `import` to `default` to import the default export. + +```ts +const modules = import.meta.glob('./dir/*.js', { + import: 'default', + eager: true +}) +``` + +```ts +// code produced by vite: +import __glob__0_0 from './dir/foo.js' +import __glob__0_1 from './dir/bar.js' +const modules = { + './dir/foo.js': __glob__0_0, + './dir/bar.js': __glob__0_1 +} +``` + +#### Custom Queries + +You can also use the `query` option to provide custom queries to imports for other plugins to consume. + +```ts +const modules = import.meta.glob('./dir/*.js', { + query: { foo: 'bar', bar: true } +}) +``` + +```ts +// code produced by vite: +const modules = { + './dir/foo.js': () => + import('./dir/foo.js?foo=bar&bar=true').then((m) => m.setup), + './dir/bar.js': () => + import('./dir/bar.js?foo=bar&bar=true').then((m) => m.setup) } ``` +### Glob Import Caveats + 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) 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. +- The glob matching is done via [`fast-glob`](https://github.com/mrmlnc/fast-glob) - check out its documentation for [supported glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax). +- You should also be aware that all the arguments in the `import.meta.glob` must be **passed as literals**. You can NOT use variables or expressions in them. ## WebAssembly diff --git a/docs/guide/index.md b/docs/guide/index.md index ff0d3f21b90e65..338bd42a565aa3 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -38,7 +38,7 @@ The supported template presets are: ## Scaffolding Your First Vite Project ::: tip Compatibility Note -Vite requires [Node.js](https://nodejs.org/en/) version >=12.2.0. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. +Vite requires [Node.js](https://nodejs.org/en/) version >=14.6.0. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. ::: With NPM: @@ -113,7 +113,7 @@ Running `vite` starts the dev server using the current working directory as root ## Command Line Interface -In a project where Vite is installed, you can use the `vite` binary in your npm scripts, or run it directly with `npx vite`. Here is the default npm scripts in a scaffolded Vite project: +In a project where Vite is installed, you can use the `vite` binary in your npm scripts, or run it directly with `npx vite`. Here are the default npm scripts in a scaffolded Vite project: ```json5 diff --git a/docs/guide/ssr.md b/docs/guide/ssr.md index d1fca329abd58d..1abd4874bca0e2 100644 --- a/docs/guide/ssr.md +++ b/docs/guide/ssr.md @@ -22,8 +22,8 @@ If you have questions, the community is usually helpful at [Vite Discord's #ssr Vite provides built-in support for server-side rendering (SSR). The Vite playground contains example SSR setups for Vue 3 and React, which can be used as references for this guide: -- [Vue 3](https://github.com/vitejs/vite/tree/main/packages/playground/ssr-vue) -- [React](https://github.com/vitejs/vite/tree/main/packages/playground/ssr-react) +- [Vue 3](https://github.com/vitejs/vite/tree/main/playground/ssr-vue) +- [React](https://github.com/vitejs/vite/tree/main/playground/ssr-react) ## Source Structure @@ -177,7 +177,7 @@ Then, in `server.js` we need to add some production specific logic by checking ` - Move the creation and all usage of the `vite` dev server behind dev-only conditional branches, then add static file serving middlewares to serve files from `dist/client`. -Refer to the [Vue](https://github.com/vitejs/vite/tree/main/packages/playground/ssr-vue) and [React](https://github.com/vitejs/vite/tree/main/packages/playground/ssr-react) demos for working setup. +Refer to the [Vue](https://github.com/vitejs/vite/tree/main/playground/ssr-vue) and [React](https://github.com/vitejs/vite/tree/main/playground/ssr-react) demos for working setup. ## Generating Preload Directives @@ -201,11 +201,11 @@ const html = await vueServerRenderer.renderToString(app, ctx) // ctx.modules is now a Set of module IDs that were used during the render ``` -In the production branch of `server.js` we need to read and pass the manifest to the `render` function exported by `src/entry-server.js`. This would provide us with enough information to render preload directives for files used by async routes! See [demo source](https://github.com/vitejs/vite/blob/main/packages/playground/ssr-vue/src/entry-server.js) for full example. +In the production branch of `server.js` we need to read and pass the manifest to the `render` function exported by `src/entry-server.js`. This would provide us with enough information to render preload directives for files used by async routes! See [demo source](https://github.com/vitejs/vite/blob/main/playground/ssr-vue/src/entry-server.js) for full example. ## Pre-Rendering / SSG -If the routes and the data needed for certain routes are known ahead of time, we can pre-render these routes into static HTML using the same logic as production SSR. This can also be considered a form of Static-Site Generation (SSG). See [demo pre-render script](https://github.com/vitejs/vite/blob/main/packages/playground/ssr-vue/prerender.js) for working example. +If the routes and the data needed for certain routes are known ahead of time, we can pre-render these routes into static HTML using the same logic as production SSR. This can also be considered a form of Static-Site Generation (SSG). See [demo pre-render script](https://github.com/vitejs/vite/blob/main/playground/ssr-vue/prerender.js) for working example. ## SSR Externals diff --git a/jest.config.ts b/jest.config.ts deleted file mode 100644 index 11663af4e08107..00000000000000 --- a/jest.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -// eslint-disable-next-line node/no-extraneous-import -import type { Config } from '@jest/types' - -const config: Config.InitialOptions = { - preset: 'ts-jest', - testMatch: process.env.VITE_TEST_BUILD - ? ['**/playground/**/*.spec.[jt]s?(x)'] - : ['**/*.spec.[jt]s?(x)'], - testTimeout: process.env.CI ? 50000 : 20000, - globalSetup: './scripts/jestGlobalSetup.cjs', - globalTeardown: './scripts/jestGlobalTeardown.cjs', - testEnvironment: './scripts/jestEnv.cjs', - setupFilesAfterEnv: ['./scripts/jestPerTestSetup.ts'], - watchPathIgnorePatterns: ['/packages/temp'], - modulePathIgnorePatterns: ['/packages/temp'], - moduleNameMapper: { - testUtils: '/packages/playground/testUtils.ts' - }, - globals: { - 'ts-jest': { - tsconfig: './packages/playground/tsconfig.json' - } - } -} - -export default config diff --git a/netlify.toml b/netlify.toml index ba9d1c55f567c5..ba62bdbe4d6be1 100644 --- a/netlify.toml +++ b/netlify.toml @@ -3,4 +3,4 @@ NPM_FLAGS = "--version" # prevent Netlify npm install [build] publish = "docs/.vitepress/dist" - command = "npx pnpm i --store=node_modules/.pnpm-store && npm run ci-docs" \ No newline at end of file + command = "npx pnpm@6 i --store=node_modules/.pnpm-store --frozen-lockfile && npx pnpm@6 run ci-docs" \ No newline at end of file diff --git a/package.json b/package.json index 1bfa2c4e77619c..6a8dca7f34a1a5 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vite-monorepo", "private": true, "engines": { - "node": ">=12.2.0" + "node": ">=14.6.0" }, "homepage": "https://vitejs.dev/", "keywords": [ @@ -15,17 +15,19 @@ "scripts": { "preinstall": "npx only-allow pnpm", "format": "prettier --write .", - "lint": "eslint packages/*/{src,types}/**", - "test": "run-s test-serve test-build", - "test-serve": "jest", - "debug-serve": "cross-env VITE_DEBUG_SERVE=1 node --inspect-brk ./node_modules/.bin/jest", - "test-build": "cross-env VITE_TEST_BUILD=1 jest", - "debug-build": "cross-env VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 node --inspect-brk ./node_modules/.bin/jest", + "lint": "eslint packages/*/{src,types}/** playground/**/__tests__/** scripts/**", + "test": "run-s test-unit test-serve test-build", + "test-serve": "vitest run -c vitest.config.e2e.ts", + "test-build": "cross-env VITE_TEST_BUILD=1 vitest run -c vitest.config.e2e.ts", + "test-unit": "vitest run", + "debug-serve": "cross-env VITE_DEBUG_SERVE=1 vitest run -c vitest.config.e2e.ts", + "debug-build": "cross-env VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 vitest run -c vitest.config.e2e.ts", "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", + "typecheck": "tsc -p scripts --noEmit && tsc -p playground --noEmit", "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", @@ -34,41 +36,56 @@ "ci-docs": "run-s build-vite build-plugin-vue build-docs" }, "devDependencies": { - "@microsoft/api-extractor": "^7.22.2", + "@microsoft/api-extractor": "^7.23.1", + "@types/babel__core": "^7.1.19", + "@types/convert-source-map": "^1.5.2", + "@types/cross-spawn": "^6.0.2", + "@types/debug": "^4.1.7", + "@types/estree": "^0.0.51", + "@types/etag": "^1.8.1", "@types/fs-extra": "^9.0.13", - "@types/jest": "^27.4.1", - "@types/node": "^17.0.25", - "@types/prompts": "^2.0.14", + "@types/hash-sum": "^1.0.0", + "@types/less": "^3.0.3", + "@types/micromatch": "^4.0.2", + "@types/mime": "^2.0.3", + "@types/node": "^17.0.31", + "@types/prompts": "^2.4.0", + "@types/resolve": "^1.20.2", + "@types/sass": "~1.43.1", "@types/semver": "^7.3.9", - "@typescript-eslint/eslint-plugin": "^5.20.0", - "@typescript-eslint/parser": "^5.20.0", + "@types/stylus": "^0.48.37", + "@types/ws": "^8.5.3", + "@typescript-eslint/eslint-plugin": "^5.22.0", + "@typescript-eslint/parser": "^5.22.0", "conventional-changelog-cli": "^2.2.2", "cross-env": "^7.0.3", - "esbuild": "^0.14.27", - "eslint": "^8.13.0", + "esbuild": "^0.14.38", + "eslint": "^8.15.0", "eslint-define-config": "^1.4.0", + "eslint-plugin-import": "^2.26.0", "eslint-plugin-node": "^11.1.0", "execa": "^5.1.1", "fs-extra": "^10.1.0", - "jest": "^27.5.1", - "lint-staged": "^12.4.0", + "kill-port": "^1.6.1", + "lint-staged": "^12.4.1", "minimist": "^1.2.6", - "node-fetch": "^2.6.6", + "node-fetch": "^2.6.7", "npm-run-all": "^4.1.5", "picocolors": "^1.0.0", "playwright-chromium": "^1.21.1", "prettier": "2.6.2", "prompts": "^2.4.2", "rimraf": "^3.0.2", - "rollup": "^2.59.0", + "rollup": "^2.72.1", "semver": "^7.3.7", "simple-git-hooks": "^2.7.0", "sirv": "^2.0.2", - "ts-jest": "^27.1.4", - "ts-node": "^10.4.0", - "typescript": "~4.5.4", + "ts-node": "^10.7.0", + "typescript": "^4.6.4", "vite": "workspace:*", - "vitepress": "^0.22.3" + "vitepress": "^0.22.4", + "vitest": "^0.12.4", + "vue": "^3.2.33" }, "simple-git-hooks": { "pre-commit": "pnpm exec lint-staged --concurrent false", @@ -79,13 +96,16 @@ "prettier --write --ignore-unknown" ], "packages/*/{src,types}/**/*.ts": [ - "eslint --ext .ts" + "eslint --fix" ], "packages/**/*.d.ts": [ - "eslint --ext .ts" + "eslint --fix" + ], + "playground/**/__tests__/**/*.ts": [ + "eslint --fix" ] }, - "packageManager": "pnpm@6.32.9", + "packageManager": "pnpm@7.0.1", "pnpm": { "overrides": { "vite": "workspace:*", diff --git a/packages/create-vite/CHANGELOG.md b/packages/create-vite/CHANGELOG.md index 7379feb81239b8..d8759a4e269c97 100644 --- a/packages/create-vite/CHANGELOG.md +++ b/packages/create-vite/CHANGELOG.md @@ -1,3 +1,10 @@ +## 2.9.3 (2022-05-02) + +* chore(create-vite): update reference to volar vscode extension (#7994) ([2b6d8fe](https://github.com/vitejs/vite/commit/2b6d8fe)), closes [#7994](https://github.com/vitejs/vite/issues/7994) +* feat(create-vite): scaffold directory with only .git (#7971) ([a5bdb9f](https://github.com/vitejs/vite/commit/a5bdb9f)), closes [#7971](https://github.com/vitejs/vite/issues/7971) + + + ## 2.9.2 (2022-04-19) * chore: remove useless code in preact template (#7789) ([e5729be](https://github.com/vitejs/vite/commit/e5729be)), closes [#7789](https://github.com/vitejs/vite/issues/7789) diff --git a/packages/create-vite/README.md b/packages/create-vite/README.md index 79d5ae12d93597..e22c268ab99f9c 100644 --- a/packages/create-vite/README.md +++ b/packages/create-vite/README.md @@ -3,7 +3,7 @@ ## Scaffolding Your First Vite Project > **Compatibility Note:** -> Vite requires [Node.js](https://nodejs.org/en/) version >=12.2.0. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. +> Vite requires [Node.js](https://nodejs.org/en/) version >=14.6.0. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. With NPM: diff --git a/packages/create-vite/__tests__/cli.spec.ts b/packages/create-vite/__tests__/cli.spec.ts index c52998172149e6..fbfb606f486885 100644 --- a/packages/create-vite/__tests__/cli.spec.ts +++ b/packages/create-vite/__tests__/cli.spec.ts @@ -3,6 +3,7 @@ import type { ExecaSyncReturnValue, SyncOptions } from 'execa' import { commandSync } from 'execa' import { mkdirpSync, readdirSync, remove, writeFileSync } from 'fs-extra' import { join } from 'path' +import { test, expect, beforeAll, afterEach } from 'vitest' const CLI_PATH = join(__dirname, '..') diff --git a/packages/create-vite/index.js b/packages/create-vite/index.js index cc0a78639755bb..981c7aa7f6fa2f 100755 --- a/packages/create-vite/index.js +++ b/packages/create-vite/index.js @@ -132,7 +132,9 @@ async function init() { let targetDir = argv._[0] let template = argv.template || argv.t - const defaultProjectName = !targetDir ? 'vite-project' : targetDir + const defaultProjectName = !targetDir + ? 'vite-project' + : targetDir.trim().replace(/\/+$/g, '') let result = {} @@ -145,7 +147,8 @@ async function init() { message: reset('Project name:'), initial: defaultProjectName, onState: (state) => - (targetDir = state.value.trim() || defaultProjectName) + (targetDir = + state.value.trim().replace(/\/+$/g, '') || defaultProjectName) }, { type: () => @@ -227,7 +230,7 @@ async function init() { if (overwrite) { emptyDir(root) } else if (!fs.existsSync(root)) { - fs.mkdirSync(root) + fs.mkdirSync(root, { recursive: true }) } // determine template @@ -313,7 +316,8 @@ function copyDir(srcDir, destDir) { } function isEmpty(path) { - return fs.readdirSync(path).length === 0 + const files = fs.readdirSync(path) + return files.length === 0 || (files.length === 1 && files[0] === '.git') } function emptyDir(dir) { diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json index 5a21b499d9b75d..38ffa81a2768ee 100644 --- a/packages/create-vite/package.json +++ b/packages/create-vite/package.json @@ -1,6 +1,6 @@ { "name": "create-vite", - "version": "2.9.2", + "version": "2.9.3", "license": "MIT", "author": "Evan You", "bin": { @@ -13,7 +13,7 @@ ], "main": "index.js", "engines": { - "node": ">=12.0.0" + "node": ">=14.6.0" }, "repository": { "type": "git", diff --git a/packages/create-vite/template-lit-ts/package.json b/packages/create-vite/template-lit-ts/package.json index eb6849d447795c..40b05d66af64f2 100644 --- a/packages/create-vite/template-lit-ts/package.json +++ b/packages/create-vite/template-lit-ts/package.json @@ -2,9 +2,9 @@ "name": "vite-lit-ts-starter", "private": true, "version": "0.0.0", - "main": "dist/my-element.es.js", + "main": "dist/my-element.es.mjs", "exports": { - ".": "./dist/my-element.es.js" + ".": "./dist/my-element.es.mjs" }, "types": "types/my-element.d.ts", "files": [ @@ -16,10 +16,10 @@ "build": "tsc && vite build" }, "dependencies": { - "lit": "^2.0.2" + "lit": "^2.2.3" }, "devDependencies": { - "vite": "^2.9.5", - "typescript": "^4.5.4" + "typescript": "^4.6.4", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-lit/package.json b/packages/create-vite/template-lit/package.json index 6fc110706147f7..ca610090e22759 100644 --- a/packages/create-vite/template-lit/package.json +++ b/packages/create-vite/template-lit/package.json @@ -2,9 +2,9 @@ "name": "vite-lit-starter", "private": true, "version": "0.0.0", - "main": "dist/my-element.es.js", + "main": "dist/my-element.es.mjs", "exports": { - ".": "./dist/my-element.es.js" + ".": "./dist/my-element.es.mjs" }, "files": [ "dist" @@ -14,9 +14,9 @@ "build": "vite build" }, "dependencies": { - "lit": "^2.0.2" + "lit": "^2.2.3" }, "devDependencies": { - "vite": "^2.9.5" + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-preact-ts/package.json b/packages/create-vite/template-preact-ts/package.json index ac90637925896f..dfff04ee49f099 100644 --- a/packages/create-vite/template-preact-ts/package.json +++ b/packages/create-vite/template-preact-ts/package.json @@ -8,11 +8,11 @@ "preview": "vite preview" }, "dependencies": { - "preact": "^10.5.15" + "preact": "^10.7.2" }, "devDependencies": { - "@preact/preset-vite": "^2.1.5", - "typescript": "^4.5.4", - "vite": "^2.9.5" + "@preact/preset-vite": "^2.2.0", + "typescript": "^4.6.4", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-preact/package.json b/packages/create-vite/template-preact/package.json index f58b6525abaa52..90cf6755ee8907 100644 --- a/packages/create-vite/template-preact/package.json +++ b/packages/create-vite/template-preact/package.json @@ -8,10 +8,10 @@ "preview": "vite preview" }, "dependencies": { - "preact": "^10.5.15" + "preact": "^10.7.2" }, "devDependencies": { - "@preact/preset-vite": "^2.1.5", - "vite": "^2.9.5" + "@preact/preset-vite": "^2.2.0", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-react-ts/package.json b/packages/create-vite/template-react-ts/package.json index 01d981f51c3414..5a6ffff172f3ab 100644 --- a/packages/create-vite/template-react-ts/package.json +++ b/packages/create-vite/template-react-ts/package.json @@ -8,14 +8,14 @@ "preview": "vite preview" }, "dependencies": { - "react": "^18.0.0", - "react-dom": "^18.0.0" + "react": "^18.1.0", + "react-dom": "^18.1.0" }, "devDependencies": { - "@types/react": "^18.0.0", - "@types/react-dom": "^18.0.0", - "@vitejs/plugin-react": "^1.3.0", - "typescript": "^4.6.3", - "vite": "^2.9.5" + "@types/react": "^18.0.9", + "@types/react-dom": "^18.0.3", + "@vitejs/plugin-react": "^1.3.2", + "typescript": "^4.6.4", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-react/package.json b/packages/create-vite/template-react/package.json index 4215fdea104c30..92f2dee91fdc48 100644 --- a/packages/create-vite/template-react/package.json +++ b/packages/create-vite/template-react/package.json @@ -8,13 +8,13 @@ "preview": "vite preview" }, "dependencies": { - "react": "^18.0.0", - "react-dom": "^18.0.0" + "react": "^18.1.0", + "react-dom": "^18.1.0" }, "devDependencies": { - "@types/react": "^18.0.0", - "@types/react-dom": "^18.0.0", - "@vitejs/plugin-react": "^1.3.0", - "vite": "^2.9.5" + "@types/react": "^18.0.9", + "@types/react-dom": "^18.0.3", + "@vitejs/plugin-react": "^1.3.2", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-svelte-ts/package.json b/packages/create-vite/template-svelte-ts/package.json index ae5bf6219d8eee..94cb978899ed0b 100644 --- a/packages/create-vite/template-svelte-ts/package.json +++ b/packages/create-vite/template-svelte-ts/package.json @@ -10,13 +10,13 @@ "check": "svelte-check --tsconfig ./tsconfig.json" }, "devDependencies": { - "@sveltejs/vite-plugin-svelte": "^1.0.0-next.30", + "@sveltejs/vite-plugin-svelte": "^1.0.0-next.43", "@tsconfig/svelte": "^2.0.1", - "svelte": "^3.44.0", - "svelte-check": "^2.2.7", - "svelte-preprocess": "^4.9.8", - "tslib": "^2.3.1", - "typescript": "^4.5.4", - "vite": "^2.9.5" + "svelte": "^3.48.0", + "svelte-check": "^2.7.0", + "svelte-preprocess": "^4.10.6", + "tslib": "^2.4.0", + "typescript": "^4.6.4", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-svelte/package.json b/packages/create-vite/template-svelte/package.json index ac224a274d1c10..7153b3389662e0 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": "^1.0.0-next.30", - "svelte": "^3.44.0", - "vite": "^2.9.5" + "@sveltejs/vite-plugin-svelte": "^1.0.0-next.43", + "svelte": "^3.48.0", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-vanilla-ts/package.json b/packages/create-vite/template-vanilla-ts/package.json index 94a8ccc952012a..8dd9deee768e4c 100644 --- a/packages/create-vite/template-vanilla-ts/package.json +++ b/packages/create-vite/template-vanilla-ts/package.json @@ -8,7 +8,7 @@ "preview": "vite preview" }, "devDependencies": { - "typescript": "^4.5.4", - "vite": "^2.9.5" + "typescript": "^4.6.4", + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-vanilla/package.json b/packages/create-vite/template-vanilla/package.json index ddc9844be1954f..b1ce70c284540f 100644 --- a/packages/create-vite/template-vanilla/package.json +++ b/packages/create-vite/template-vanilla/package.json @@ -8,6 +8,6 @@ "preview": "vite preview" }, "devDependencies": { - "vite": "^2.9.5" + "vite": "^2.9.8" } } diff --git a/packages/create-vite/template-vue-ts/.vscode/extensions.json b/packages/create-vite/template-vue-ts/.vscode/extensions.json index 3dc5b08bcdc96b..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": ["johnsoncodehk.volar"] + "recommendations": ["Vue.volar"] } diff --git a/packages/create-vite/template-vue-ts/README.md b/packages/create-vite/template-vue-ts/README.md index e432516724c1a7..30b15e215a24b7 100644 --- a/packages/create-vite/template-vue-ts/README.md +++ b/packages/create-vite/template-vue-ts/README.md @@ -4,7 +4,7 @@ This template should help get you started developing with Vue 3 and TypeScript i ## Recommended IDE Setup -- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=johnsoncodehk.volar) +- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) ## Type Support For `.vue` Imports in TS diff --git a/packages/create-vite/template-vue-ts/package.json b/packages/create-vite/template-vue-ts/package.json index c7383d48b09e3b..38f22b1ff17513 100644 --- a/packages/create-vite/template-vue-ts/package.json +++ b/packages/create-vite/template-vue-ts/package.json @@ -8,12 +8,12 @@ "preview": "vite preview" }, "dependencies": { - "vue": "^3.2.25" + "vue": "^3.2.33" }, "devDependencies": { - "@vitejs/plugin-vue": "^2.3.1", - "typescript": "^4.5.4", - "vite": "^2.9.5", - "vue-tsc": "^0.34.7" + "@vitejs/plugin-vue": "^2.3.2", + "typescript": "^4.6.4", + "vite": "^2.9.8", + "vue-tsc": "^0.34.11" } } diff --git a/packages/create-vite/template-vue/.vscode/extensions.json b/packages/create-vite/template-vue/.vscode/extensions.json index 3dc5b08bcdc96b..a7cea0b0678120 100644 --- a/packages/create-vite/template-vue/.vscode/extensions.json +++ b/packages/create-vite/template-vue/.vscode/extensions.json @@ -1,3 +1,3 @@ { - "recommendations": ["johnsoncodehk.volar"] + "recommendations": ["Vue.volar"] } diff --git a/packages/create-vite/template-vue/README.md b/packages/create-vite/template-vue/README.md index eea15cef41ea60..02124a7a0a92bc 100644 --- a/packages/create-vite/template-vue/README.md +++ b/packages/create-vite/template-vue/README.md @@ -4,4 +4,4 @@ This template should help get you started developing with Vue 3 in Vite. The tem ## Recommended IDE Setup -- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=johnsoncodehk.volar) +- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) diff --git a/packages/create-vite/template-vue/package.json b/packages/create-vite/template-vue/package.json index e7e9b681db608c..dd12fbbfda53a9 100644 --- a/packages/create-vite/template-vue/package.json +++ b/packages/create-vite/template-vue/package.json @@ -8,10 +8,10 @@ "preview": "vite preview" }, "dependencies": { - "vue": "^3.2.25" + "vue": "^3.2.33" }, "devDependencies": { - "@vitejs/plugin-vue": "^2.3.1", - "vite": "^2.9.5" + "@vitejs/plugin-vue": "^2.3.2", + "vite": "^2.9.8" } } diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts deleted file mode 100644 index 75c0e57952db24..00000000000000 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ /dev/null @@ -1,316 +0,0 @@ -import { createHash } from 'crypto' -import { - findAssetFile, - getBg, - getColor, - isBuild, - listAssets, - readManifest, - readFile, - editFile, - notifyRebuildComplete, - untilUpdated -} from '../../testUtils' - -const assetMatch = isBuild - ? /\/foo\/assets\/asset\.\w{8}\.png/ - : '/foo/nested/asset.png' - -const iconMatch = `/foo/icon.png` - -test('should have no 404s', () => { - browserLogs.forEach((msg) => { - expect(msg).not.toMatch('404') - }) -}) - -describe('injected scripts', () => { - test('@vite/client', async () => { - const hasClient = await page.$( - 'script[type="module"][src="/foo/@vite/client"]' - ) - if (isBuild) { - expect(hasClient).toBeFalsy() - } else { - expect(hasClient).toBeTruthy() - } - }) - - test('html-proxy', async () => { - const hasHtmlProxy = await page.$( - 'script[type="module"][src^="/foo/index.html?html-proxy"]' - ) - if (isBuild) { - expect(hasHtmlProxy).toBeFalsy() - } else { - expect(hasHtmlProxy).toBeTruthy() - } - }) -}) - -describe('raw references from /public', () => { - test('load raw js from /public', async () => { - expect(await page.textContent('.raw-js')).toMatch('[success]') - }) - - test('load raw css from /public', async () => { - expect(await getColor('.raw-css')).toBe('red') - }) -}) - -test('import-expression from simple script', async () => { - expect(await page.textContent('.import-expression')).toMatch( - '[success][success]' - ) -}) - -describe('asset imports from js', () => { - test('relative', async () => { - expect(await page.textContent('.asset-import-relative')).toMatch(assetMatch) - }) - - test('absolute', async () => { - expect(await page.textContent('.asset-import-absolute')).toMatch(assetMatch) - }) - - test('from /public', async () => { - expect(await page.textContent('.public-import')).toMatch(iconMatch) - }) -}) - -describe('css url() references', () => { - test('fonts', async () => { - expect( - await page.evaluate(() => { - return (document as any).fonts.check('700 32px Inter') - }) - ).toBe(true) - }) - - test('relative', async () => { - expect(await getBg('.css-url-relative')).toMatch(assetMatch) - }) - - test('image-set relative', async () => { - const imageSet = await getBg('.css-image-set-relative') - imageSet.split(', ').forEach((s) => { - expect(s).toMatch(assetMatch) - }) - }) - - test('image-set without the url() call', async () => { - const imageSet = await getBg('.css-image-set-without-url-call') - imageSet.split(', ').forEach((s) => { - expect(s).toMatch(assetMatch) - }) - }) - - test('relative in @import', async () => { - expect(await getBg('.css-url-relative-at-imported')).toMatch(assetMatch) - }) - - test('absolute', async () => { - expect(await getBg('.css-url-absolute')).toMatch(assetMatch) - }) - - test('from /public', async () => { - expect(await getBg('.css-url-public')).toMatch(iconMatch) - }) - - test('base64 inline', async () => { - 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 () => { - const bg = await getBg('.css-url-same-line') - expect(bg).toMatch(assetMatch) - expect(bg).toMatch(iconMatch) - }) - - test('aliased', async () => { - const bg = await getBg('.css-url-aliased') - expect(bg).toMatch(assetMatch) - }) - - if (isBuild) { - test('preserve postfix query/hash', () => { - expect(findAssetFile(/\.css$/, 'foo')).toMatch(`woff2?#iefix`) - }) - } -}) - -describe('image', () => { - test('srcset', async () => { - const img = await page.$('.img-src-set') - const srcset = await img.getAttribute('srcset') - srcset.split(', ').forEach((s) => { - expect(s).toMatch( - isBuild - ? /\/foo\/assets\/asset\.\w{8}\.png \d{1}x/ - : /\.\/nested\/asset\.png \d{1}x/ - ) - }) - }) -}) - -describe('svg fragments', () => { - // 404 is checked already, so here we just ensure the urls end with #fragment - test('img url', async () => { - const img = await page.$('.svg-frag-img') - expect(await img.getAttribute('src')).toMatch(/svg#icon-clock-view$/) - }) - - test('via css url()', async () => { - const bg = await page.evaluate(() => { - return getComputedStyle(document.querySelector('.icon')).backgroundImage - }) - expect(bg).toMatch(/svg#icon-clock-view"\)$/) - }) - - test('from js import', async () => { - const img = await page.$('.svg-frag-import') - expect(await img.getAttribute('src')).toMatch(/svg#icon-heart-view$/) - }) -}) - -test('?raw import', async () => { - expect(await page.textContent('.raw')).toMatch('SVG') -}) - -test('?url import', async () => { - const src = readFile('foo.js') - expect(await page.textContent('.url')).toMatch( - isBuild - ? `data:application/javascript;base64,${Buffer.from(src).toString( - 'base64' - )}` - : `/foo/foo.js` - ) -}) - -test('?url import on css', async () => { - const src = readFile('css/icons.css') - const txt = await page.textContent('.url-css') - expect(txt).toEqual( - isBuild - ? `data:text/css;base64,${Buffer.from(src).toString('base64')}` - : '/foo/css/icons.css' - ) -}) - -describe('unicode url', () => { - test('from js import', async () => { - const src = readFile('テスト-測試-white space.js') - expect(await page.textContent('.unicode-url')).toMatch( - isBuild - ? `data:application/javascript;base64,${Buffer.from(src).toString( - 'base64' - )}` - : `/foo/テスト-測試-white space.js` - ) - }) -}) - -describe('encodeURI', () => { - if (isBuild) { - test('img src with encodeURI', async () => { - const img = await page.$('.encodeURI') - expect( - await ( - await img.getAttribute('src') - ).startsWith('data:image/png;base64') - ).toBe(true) - }) - } -}) - -test('new URL(..., import.meta.url)', async () => { - expect(await page.textContent('.import-meta-url')).toMatch(assetMatch) -}) - -test('new URL(`${dynamic}`, import.meta.url)', async () => { - expect(await page.textContent('.dynamic-import-meta-url-1')).toMatch( - isBuild ? 'data:image/png;base64' : '/foo/nested/icon.png' - ) - expect(await page.textContent('.dynamic-import-meta-url-2')).toMatch( - assetMatch - ) -}) - -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') - const entry = manifest['index.html'] - - for (const file of listAssets('foo')) { - if (file.endsWith('.css')) { - expect(entry.css).toContain(`assets/${file}`) - } else if (!file.endsWith('.js')) { - expect(entry.assets).toContain(`assets/${file}`) - } - } - }) -} - -describe('css and assets in css in build watch', () => { - if (isBuild) { - test('css will not be lost and css does not contain undefined', async () => { - editFile('index.html', (code) => code.replace('Assets', 'assets'), true) - await notifyRebuildComplete(watcher) - const cssFile = findAssetFile(/index\.\w+\.css$/, 'foo') - expect(cssFile).not.toBe('') - expect(cssFile).not.toMatch(/undefined/) - }) - - test('import module.css', async () => { - expect(await getColor('#foo')).toBe('red') - editFile( - 'css/foo.module.css', - (code) => code.replace('red', 'blue'), - true - ) - await notifyRebuildComplete(watcher) - await page.reload() - expect(await getColor('#foo')).toBe('blue') - }) - - test('import with raw query', async () => { - expect(await page.textContent('.raw-query')).toBe('foo') - editFile('static/foo.txt', (code) => code.replace('foo', 'zoo'), true) - await notifyRebuildComplete(watcher) - await page.reload() - expect(await page.textContent('.raw-query')).toBe('zoo') - }) - } -}) - -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)') - }) -} - -test('html import word boundary', async () => { - expect(await page.textContent('.obj-import-express')).toMatch( - 'ignore object import prop' - ) - expect(await page.textContent('.string-import-express')).toMatch('no load') -}) diff --git a/packages/playground/assets/css/css-url.css b/packages/playground/assets/css/css-url.css deleted file mode 100644 index 8a3f00dee17bd9..00000000000000 --- a/packages/playground/assets/css/css-url.css +++ /dev/null @@ -1,66 +0,0 @@ -@import './nested/at-imported-css-url.css'; - -.css-url-absolute { - background: url(/nested/asset.png); - background-size: 10px; -} - -.css-url-relative { - background: url(../nested/asset.png); - background-size: 10px; -} - -.css-image-set-relative { - background-image: -webkit-image-set( - url('../nested/asset.png') 1x, - url('../nested/asset.png') 2x - ); - background-size: 10px; -} - -.css-image-set-without-url-call { - background-image: -webkit-image-set( - '../nested/asset.png' 1x, - '../nested/asset.png' 2x - ); - background-size: 10px; -} - -.css-url-public { - background: url('/icon.png'); - background-size: 10px; -} - -.css-url-data-uri { - background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=); - background-size: 10px; -} - -.css-url-base64-inline { - background: url(../nested/icon.png); - background-size: 10px; -} - -.css-url-quotes-base64-inline { - background: url('../nested/icon.png'); - background-size: 10px; -} - -.css-url-same-line { - background: url('/nested/asset.png') top right / 10px no-repeat, - url('/icon.png') bottom right / 10px no-repeat; -} - -.css-url-aliased { - background: url('@/asset.png'); - background-size: 10px; -} - -/* -urls inside comments should be ignored - -.css-url-relative { - background: url(../nested/non-existent.png); - background-size: 10px; -} -*/ diff --git a/packages/playground/backend-integration/__tests__/backend-integration.spec.ts b/packages/playground/backend-integration/__tests__/backend-integration.spec.ts deleted file mode 100644 index 7eebc9c27ff05a..00000000000000 --- a/packages/playground/backend-integration/__tests__/backend-integration.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { - editFile, - getColor, - isBuild, - readManifest, - untilUpdated -} from '../../testUtils' - -const outerAssetMatch = isBuild - ? /\/dev\/assets\/logo\.\w{8}\.png/ - : /\/dev\/@fs\/.+?\/images\/logo\.png/ - -test('should have no 404s', () => { - browserLogs.forEach((msg) => { - expect(msg).not.toMatch('404') - }) -}) - -describe('asset imports from js', () => { - test('file outside root', async () => { - expect( - await page.textContent('.asset-reference.outside-root .asset-url') - ).toMatch(outerAssetMatch) - }) -}) - -if (isBuild) { - test('manifest', async () => { - const manifest = readManifest('dev') - const htmlEntry = manifest['index.html'] - expect(htmlEntry.css.length).toEqual(1) - expect(htmlEntry.assets.length).toEqual(1) - }) -} else { - test('No ReferenceError', async () => { - browserErrors.forEach((error) => { - expect(error.name).not.toBe('ReferenceError') - }) - }) - - describe('CSS HMR', () => { - test('preserve the base in CSS HMR', async () => { - await untilUpdated(() => getColor('body'), 'black') // sanity check - editFile('frontend/entrypoints/global.css', (code) => - code.replace('black', 'red') - ) - await untilUpdated(() => getColor('body'), 'red') // successful HMR - - // Verify that the base (/dev/) was added during the css-update - const link = await page.$('link[rel="stylesheet"]') - expect(await link.getAttribute('href')).toContain('/dev/global.css?t=') - }) - - test('CSS dependencies are tracked for HMR', async () => { - const el = await page.$('h1') - browserLogs.length = 0 - - editFile('frontend/entrypoints/main.ts', (code) => - code.replace('text-black', 'text-[rgb(204,0,0)]') - ) - await untilUpdated(() => getColor(el), 'rgb(204, 0, 0)') - expect(browserLogs).toContain('[vite] css hot updated: /global.css') - }) - }) -} diff --git a/packages/playground/css-codesplit/__tests__/css-codesplit.spec.ts b/packages/playground/css-codesplit/__tests__/css-codesplit.spec.ts deleted file mode 100644 index 95fe97a1b953ba..00000000000000 --- a/packages/playground/css-codesplit/__tests__/css-codesplit.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { findAssetFile, getColor, isBuild, readManifest } from '../../testUtils' - -test('should load both stylesheets', async () => { - expect(await getColor('h1')).toBe('red') - expect(await getColor('h2')).toBe('blue') -}) - -if (isBuild) { - test('should remove empty chunk', async () => { - expect(findAssetFile(/style.*\.js$/)).toBe('') - expect(findAssetFile('main.*.js$')).toMatch(`/* empty css`) - expect(findAssetFile('other.*.js$')).toMatch(`/* empty css`) - }) - - test('should generate correct manifest', async () => { - const manifest = readManifest() - expect(manifest['index.html'].css.length).toBe(2) - expect(manifest['other.js'].css.length).toBe(1) - }) -} diff --git a/packages/playground/css-codesplit/index.html b/packages/playground/css-codesplit/index.html deleted file mode 100644 index 6b7b3bb2b4dc2d..00000000000000 --- a/packages/playground/css-codesplit/index.html +++ /dev/null @@ -1,2 +0,0 @@ - -
diff --git a/packages/playground/css-codesplit/main.js b/packages/playground/css-codesplit/main.js deleted file mode 100644 index 8c80df2c181511..00000000000000 --- a/packages/playground/css-codesplit/main.js +++ /dev/null @@ -1,6 +0,0 @@ -import './style.css' -import './main.css' - -document.getElementById( - 'app' -).innerHTML = `

This should be red

This should be blue

` diff --git a/packages/playground/css-sourcemap/__tests__/build.spec.ts b/packages/playground/css-sourcemap/__tests__/build.spec.ts deleted file mode 100644 index e36c1f52d2c1f8..00000000000000 --- a/packages/playground/css-sourcemap/__tests__/build.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isBuild } from 'testUtils' - -if (isBuild) { - test('should not output sourcemap warning (#4939)', () => { - serverLogs.forEach((log) => { - expect(log).not.toMatch('Sourcemap is likely to be incorrect') - }) - }) -} else { - test('this file only includes test for build', () => { - expect(true).toBe(true) - }) -} diff --git a/packages/playground/data-uri/__tests__/data-uri.spec.ts b/packages/playground/data-uri/__tests__/data-uri.spec.ts deleted file mode 100644 index e1d488c931e7c1..00000000000000 --- a/packages/playground/data-uri/__tests__/data-uri.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { isBuild, findAssetFile } from '../../testUtils' - -test('plain', async () => { - expect(await page.textContent('.plain')).toBe('hi') -}) - -test('base64', async () => { - expect(await page.textContent('.base64')).toBe('hi') -}) - -if (isBuild) { - test('should compile away the import for build', async () => { - const file = findAssetFile('index') - expect(file).not.toMatch('import') - }) -} diff --git a/packages/playground/dynamic-import/package.json b/packages/playground/dynamic-import/package.json deleted file mode 100644 index a6b6d5f863f1b8..00000000000000 --- a/packages/playground/dynamic-import/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "test-dynamic-import", - "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/fs-serve/__tests__/fs-serve.spec.ts b/packages/playground/fs-serve/__tests__/fs-serve.spec.ts deleted file mode 100644 index eba1e441881710..00000000000000 --- a/packages/playground/fs-serve/__tests__/fs-serve.spec.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { isBuild } from '../../testUtils' - -const json = require('../safe.json') -const stringified = JSON.stringify(json) - -describe('main', () => { - beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts - await page.goto(viteTestUrl + '/src/') - }) - - if (!isBuild) { - test('default import', async () => { - expect(await page.textContent('.full')).toBe(stringified) - }) - - test('named import', async () => { - expect(await page.textContent('.named')).toBe(json.msg) - }) - - test('safe fetch', async () => { - expect(await page.textContent('.safe-fetch')).toMatch('KEY=safe') - expect(await page.textContent('.safe-fetch-status')).toBe('200') - }) - - test('safe fetch with special characters', async () => { - expect( - await page.textContent('.safe-fetch-subdir-special-characters') - ).toMatch('KEY=safe') - expect( - await page.textContent('.safe-fetch-subdir-special-characters-status') - ).toBe('200') - }) - - test('unsafe fetch', async () => { - expect(await page.textContent('.unsafe-fetch')).toMatch('403 Restricted') - expect(await page.textContent('.unsafe-fetch-status')).toBe('403') - }) - - test('safe fs fetch', async () => { - expect(await page.textContent('.safe-fs-fetch')).toBe(stringified) - expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') - }) - - test('safe fs fetch with special characters', async () => { - expect(await page.textContent('.safe-fs-fetch-special-characters')).toBe( - stringified - ) - expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') - }) - - test('unsafe fs fetch', async () => { - expect(await page.textContent('.unsafe-fs-fetch')).toBe('') - expect(await page.textContent('.unsafe-fs-fetch-status')).toBe('403') - }) - - test('nested entry', async () => { - expect(await page.textContent('.nested-entry')).toBe('foobar') - }) - - test('nested entry', async () => { - expect(await page.textContent('.nested-entry')).toBe('foobar') - }) - - test('denied', async () => { - expect(await page.textContent('.unsafe-dotenv')).toBe('404') - }) - } else { - test('dummy test to make jest happy', async () => { - // Your test suite must contain at least one test. - }) - } -}) diff --git a/packages/playground/glob-import/dir/index.js b/packages/playground/glob-import/dir/index.js deleted file mode 100644 index fb87f69f0f3a61..00000000000000 --- a/packages/playground/glob-import/dir/index.js +++ /dev/null @@ -1,4 +0,0 @@ -const modules = import.meta.globEager('./*.(js|ts)') -const globWithAlias = import.meta.globEager('@dir/al*.js') - -export { modules, globWithAlias } diff --git a/packages/playground/glob-import/dir/nested/bar.js b/packages/playground/glob-import/dir/nested/bar.js deleted file mode 100644 index a2d2921cca80ad..00000000000000 --- a/packages/playground/glob-import/dir/nested/bar.js +++ /dev/null @@ -1,4 +0,0 @@ -const modules = import.meta.globEager('../*.json') - -export const msg = 'bar' -export { modules } diff --git a/packages/playground/glob-import/side-effect/writetodom.js b/packages/playground/glob-import/side-effect/writetodom.js new file mode 100644 index 00000000000000..e2ab04ba7f5cbe --- /dev/null +++ b/packages/playground/glob-import/side-effect/writetodom.js @@ -0,0 +1,4 @@ +/* global document */ +document && + (document.querySelector('.side-effect-result').textContent = + 'Hello from side effect') diff --git a/packages/playground/js-sourcemap/__tests__/build.spec.ts b/packages/playground/js-sourcemap/__tests__/build.spec.ts deleted file mode 100644 index e36c1f52d2c1f8..00000000000000 --- a/packages/playground/js-sourcemap/__tests__/build.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isBuild } from 'testUtils' - -if (isBuild) { - test('should not output sourcemap warning (#4939)', () => { - serverLogs.forEach((log) => { - expect(log).not.toMatch('Sourcemap is likely to be incorrect') - }) - }) -} else { - test('this file only includes test for build', () => { - expect(true).toBe(true) - }) -} diff --git a/packages/playground/json/index.ssr.html b/packages/playground/json/index.ssr.html new file mode 100644 index 00000000000000..8a4c4551a90817 --- /dev/null +++ b/packages/playground/json/index.ssr.html @@ -0,0 +1,23 @@ +
+ json-module: +

+  
+
+
+ json-fs: +

+  
+
+ + diff --git a/packages/playground/json/package.json b/packages/playground/json/package.json deleted file mode 100644 index 203846bab73b48..00000000000000 --- a/packages/playground/json/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "test-json", - "private": true, - "version": "0.0.0", - "scripts": { - "dev": "vite", - "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", - "preview": "vite preview" - }, - "devDependencies": { - "vue": "^3.2.25", - "json-module": "file:./json-module" - } -} diff --git a/packages/playground/json/server.js b/packages/playground/json/server.js new file mode 100644 index 00000000000000..d7803b94f4b81a --- /dev/null +++ b/packages/playground/json/server.js @@ -0,0 +1,88 @@ +// @ts-check +const fs = require('fs') +const path = require('path') +const express = require('express') + +const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD + +async function createServer( + root = process.cwd(), + isProd = process.env.NODE_ENV === 'production' +) { + const resolve = (p) => path.resolve(__dirname, p) + const app = express() + + /** + * @type {import('vite').ViteDevServer} + */ + let vite + vite = await require('vite').createServer({ + root, + logLevel: isTest ? 'error' : 'info', + server: { + middlewareMode: 'ssr', + watch: { + // During tests we edit the files too fast and sometimes chokidar + // misses change events, so enforce polling for consistency + usePolling: true, + interval: 100 + } + }, + json: { + stringify: true + } + }) + // use vite's connect instance as middleware + app.use(vite.middlewares) + + app.use('*', async (req, res) => { + try { + let [url] = req.originalUrl.split('?') + if (url.endsWith('/')) url += 'index.ssr.html' + + if (url === '/json-module') { + console.time('load module') + const json = JSON.stringify(await vite.ssrLoadModule('/test.json')) + console.timeEnd('load module') + res.status(200).end('' + json.length) + return + } + + if (url === '/json-fs') { + console.time('transform module') + const source = fs.readFileSync('./test.json', { encoding: 'utf-8' }) + const json = await vite.ssrTransform( + `export default ${source}`, + null, + './output.json' + ) + console.timeEnd('transform module') + res.status(200).end(String(json.code.length)) + return + } + + const htmlLoc = resolve(`.${url}`) + let html = fs.readFileSync(htmlLoc, 'utf8') + html = await vite.transformIndexHtml(url, html) + + res.status(200).set({ 'Content-Type': 'text/html' }).end(html) + } catch (e) { + vite && vite.ssrFixStacktrace(e) + console.log(e.stack) + res.status(500).end(e.stack) + } + }) + + return { app, vite } +} + +if (!isTest) { + createServer().then(({ app }) => + app.listen(3000, () => { + console.log('http://localhost:3000') + }) + ) +} + +// for test use +exports.createServer = createServer diff --git a/packages/playground/lib/__tests__/lib.spec.ts b/packages/playground/lib/__tests__/lib.spec.ts deleted file mode 100644 index 382fb16510ce6f..00000000000000 --- a/packages/playground/lib/__tests__/lib.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { isBuild, findAssetFile, testDir } from 'testUtils' -import path from 'path' -import fs from 'fs' - -if (isBuild) { - test('es', async () => { - expect(await page.textContent('.es')).toBe('It works') - }) - - test('umd', async () => { - expect(await page.textContent('.umd')).toBe('It works') - }) - - test('iife', async () => { - expect(await page.textContent('.iife')).toBe('It works') - }) - - test('Library mode does not include `preload`', async () => { - expect(await page.textContent('.dynamic-import-message')).toBe('hello vite') - const code = fs.readFileSync( - path.join(testDir, 'dist/lib/dynamic-import-message.js'), - 'utf-8' - ) - expect(code).not.toMatch('__vitePreload') - }) -} else { - test('dev', async () => { - expect(await page.textContent('.demo')).toBe('It works') - }) -} diff --git a/packages/playground/lib/src/main.js b/packages/playground/lib/src/main.js deleted file mode 100644 index 2422edf5829a0e..00000000000000 --- a/packages/playground/lib/src/main.js +++ /dev/null @@ -1,3 +0,0 @@ -export default function myLib(sel) { - document.querySelector(sel).textContent = 'It works' -} diff --git a/packages/playground/react/__tests__/react.spec.ts b/packages/playground/react/__tests__/react.spec.ts deleted file mode 100644 index 46eb752924f801..00000000000000 --- a/packages/playground/react/__tests__/react.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { editFile, untilUpdated, isBuild } from '../../testUtils' - -test('should render', async () => { - expect(await page.textContent('h1')).toMatch('Hello Vite + React') -}) - -test('should update', async () => { - expect(await page.textContent('button')).toMatch('count is: 0') - await page.click('button') - expect(await page.textContent('button')).toMatch('count is: 1') -}) - -test('should hmr', async () => { - editFile('App.jsx', (code) => code.replace('Vite + React', 'Updated')) - await untilUpdated(() => page.textContent('h1'), 'Hello Updated') - // preserve state - expect(await page.textContent('button')).toMatch('count is: 1') -}) - -test('should have annotated jsx with file location metadata', async () => { - // we're not annotating in prod, - // so we skip this test when isBuild is true - if (isBuild) return - - const meta = await page.evaluate(() => { - const button = document.querySelector('button') - const key = Object.keys(button).find( - (key) => key.indexOf('__reactFiber') === 0 - ) - return button[key]._debugSource - }) - // If the evaluate call doesn't crash, and the returned metadata has - // the expected fields, we're good. - expect(Object.keys(meta).sort()).toEqual([ - 'columnNumber', - 'fileName', - 'lineNumber' - ]) -}) diff --git a/packages/playground/resolve-config/__tests__/resolve-config.spec.ts b/packages/playground/resolve-config/__tests__/resolve-config.spec.ts deleted file mode 100644 index 13ea5ea6f59a4f..00000000000000 --- a/packages/playground/resolve-config/__tests__/resolve-config.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import fs from 'fs' -import path from 'path' -import { commandSync } from 'execa' -import { isBuild, testDir, workspaceRoot } from '../../testUtils' - -const viteBin = path.join(workspaceRoot, 'packages', 'vite', 'bin', 'vite.js') - -const fromTestDir = (...p: string[]) => path.resolve(testDir, ...p) - -const build = (configName: string) => { - commandSync(`${viteBin} build`, { cwd: fromTestDir(configName) }) -} -const getDistFile = (configName: string) => { - return fs.readFileSync(fromTestDir(`${configName}/dist/index.es.js`), 'utf8') -} - -if (isBuild) { - it('loads vite.config.js', () => { - build('js') - expect(getDistFile('js')).toContain('console.log(true)') - }) - it('loads vite.config.js with package#type module', () => { - build('js-module') - expect(getDistFile('js-module')).toContain('console.log(true)') - }) - it('loads vite.config.cjs', () => { - build('cjs') - expect(getDistFile('cjs')).toContain('console.log(true)') - }) - it('loads vite.config.cjs with package#type module', () => { - build('cjs-module') - expect(getDistFile('cjs-module')).toContain('console.log(true)') - }) - it('loads vite.config.mjs', () => { - build('mjs') - expect(getDistFile('mjs')).toContain('console.log(true)') - }) - it('loads vite.config.mjs with package#type module', () => { - build('mjs-module') - expect(getDistFile('mjs-module')).toContain('console.log(true)') - }) - it('loads vite.config.ts', () => { - build('ts') - expect(getDistFile('ts')).toContain('console.log(true)') - }) - it('loads vite.config.ts with package#type module', () => { - build('ts-module') - expect(getDistFile('ts-module')).toContain('console.log(true)') - }) -} else { - // this test doesn't support serve mode - // must contain at least one test - test('should work', () => void 0) -} diff --git a/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts b/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts deleted file mode 100644 index e36c1f52d2c1f8..00000000000000 --- a/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isBuild } from 'testUtils' - -if (isBuild) { - test('should not output sourcemap warning (#4939)', () => { - serverLogs.forEach((log) => { - expect(log).not.toMatch('Sourcemap is likely to be incorrect') - }) - }) -} else { - test('this file only includes test for build', () => { - expect(true).toBe(true) - }) -} diff --git a/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts b/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts deleted file mode 100644 index d961f75e4536e5..00000000000000 --- a/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isBuild } from 'testUtils' - -if (!isBuild) { - test('should not output missing source file warning', () => { - serverLogs.forEach((log) => { - expect(log).not.toMatch(/Sourcemap for .+ points to missing source files/) - }) - }) -} else { - test('this file only includes test for serve', () => { - expect(true).toBe(true) - }) -} diff --git a/packages/playground/vue-lib/__tests__/serve.js b/packages/playground/vue-lib/__tests__/serve.js deleted file mode 100644 index 73f89eee44ea3e..00000000000000 --- a/packages/playground/vue-lib/__tests__/serve.js +++ /dev/null @@ -1,7 +0,0 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace -// the default e2e test serve behavior - -exports.serve = async function serve() { - // do nothing, skip default behavior -} diff --git a/packages/playground/vue-sourcemap/__tests__/build.spec.ts b/packages/playground/vue-sourcemap/__tests__/build.spec.ts deleted file mode 100644 index e36c1f52d2c1f8..00000000000000 --- a/packages/playground/vue-sourcemap/__tests__/build.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isBuild } from 'testUtils' - -if (isBuild) { - test('should not output sourcemap warning (#4939)', () => { - serverLogs.forEach((log) => { - expect(log).not.toMatch('Sourcemap is likely to be incorrect') - }) - }) -} else { - test('this file only includes test for build', () => { - expect(true).toBe(true) - }) -} diff --git a/packages/plugin-legacy/CHANGELOG.md b/packages/plugin-legacy/CHANGELOG.md index 5c00212554ce8c..035460b5816cb5 100644 --- a/packages/plugin-legacy/CHANGELOG.md +++ b/packages/plugin-legacy/CHANGELOG.md @@ -1,3 +1,12 @@ +## 1.8.2 (2022-05-02) + +* chore(deps): update all non-major dependencies (#7780) ([eba9d05](https://github.com/vitejs/vite/commit/eba9d05)), closes [#7780](https://github.com/vitejs/vite/issues/7780) +* chore(deps): update all non-major dependencies (#7847) ([e29d1d9](https://github.com/vitejs/vite/commit/e29d1d9)), closes [#7847](https://github.com/vitejs/vite/issues/7847) +* chore(deps): update all non-major dependencies (#7949) ([b877d30](https://github.com/vitejs/vite/commit/b877d30)), closes [#7949](https://github.com/vitejs/vite/issues/7949) +* refactor(legacy): remove unneeded dynamic import var init code (#7759) ([12a4e7d](https://github.com/vitejs/vite/commit/12a4e7d)), closes [#7759](https://github.com/vitejs/vite/issues/7759) + + + ## 1.8.1 (2022-04-13) * fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) diff --git a/packages/plugin-legacy/README.md b/packages/plugin-legacy/README.md index 3c9fe67e107f7f..fc4167f4f1010f 100644 --- a/packages/plugin-legacy/README.md +++ b/packages/plugin-legacy/README.md @@ -27,22 +27,6 @@ export default { } ``` -When targeting IE11, you also need `regenerator-runtime`: - -```js -// vite.config.js -import legacy from '@vitejs/plugin-legacy' - -export default { - plugins: [ - legacy({ - targets: ['ie >= 11'], - additionalLegacyPolyfills: ['regenerator-runtime/runtime'] - }) - ] -} -``` - ## Options ### `targets` diff --git a/packages/plugin-legacy/package.json b/packages/plugin-legacy/package.json index adc97e974f2d37..296c994165747b 100644 --- a/packages/plugin-legacy/package.json +++ b/packages/plugin-legacy/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-legacy", - "version": "1.8.1", + "version": "1.8.2", "license": "MIT", "author": "Evan You", "files": [ @@ -10,7 +10,7 @@ "main": "index.js", "types": "index.d.ts", "engines": { - "node": ">=12.0.0" + "node": ">=14.6.0" }, "repository": { "type": "git", @@ -22,8 +22,8 @@ }, "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-legacy#readme", "dependencies": { - "@babel/standalone": "^7.17.9", - "core-js": "^3.22.2", + "@babel/standalone": "^7.17.11", + "core-js": "^3.22.4", "magic-string": "^0.26.1", "regenerator-runtime": "^0.13.9", "systemjs": "^6.12.1" diff --git a/packages/plugin-react/CHANGELOG.md b/packages/plugin-react/CHANGELOG.md index 958c8270b6f221..01dfee3feb7ffb 100644 --- a/packages/plugin-react/CHANGELOG.md +++ b/packages/plugin-react/CHANGELOG.md @@ -1,3 +1,11 @@ +## 1.3.2 (2022-05-02) + +* fix(plugin-react): React is not defined when component name is lowercase (#6838) ([bf40e5c](https://github.com/vitejs/vite/commit/bf40e5c)), closes [#6838](https://github.com/vitejs/vite/issues/6838) +* chore(deps): update all non-major dependencies (#7780) ([eba9d05](https://github.com/vitejs/vite/commit/eba9d05)), closes [#7780](https://github.com/vitejs/vite/issues/7780) +* chore(deps): update all non-major dependencies (#7949) ([b877d30](https://github.com/vitejs/vite/commit/b877d30)), closes [#7949](https://github.com/vitejs/vite/issues/7949) + + + ## 1.3.1 (2022-04-13) * fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) diff --git a/packages/plugin-react/package.json b/packages/plugin-react/package.json index 8c93db98aac027..ca8b1d78752b69 100644 --- a/packages/plugin-react/package.json +++ b/packages/plugin-react/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-react", - "version": "1.3.1", + "version": "1.3.2", "license": "MIT", "author": "Evan You", "contributors": [ @@ -21,7 +21,7 @@ "prepublishOnly": "(cd ../vite && npm run build) && npm run build" }, "engines": { - "node": ">=12.0.0" + "node": ">=14.6.0" }, "repository": { "type": "git", @@ -33,13 +33,16 @@ }, "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-react#readme", "dependencies": { - "@babel/core": "^7.17.9", + "@babel/core": "^7.17.10", "@babel/plugin-transform-react-jsx": "^7.17.3", "@babel/plugin-transform-react-jsx-development": "^7.16.7", "@babel/plugin-transform-react-jsx-self": "^7.16.7", "@babel/plugin-transform-react-jsx-source": "^7.16.7", "@rollup/pluginutils": "^4.2.1", - "react-refresh": "^0.12.0", + "react-refresh": "^0.13.0", "resolve": "^1.22.0" + }, + "peerDependencies": { + "vite": "^2.0.0" } } diff --git a/packages/plugin-react/src/fast-refresh.ts b/packages/plugin-react/src/fast-refresh.ts index 4672e26f6264e3..6bff7d94fa023b 100644 --- a/packages/plugin-react/src/fast-refresh.ts +++ b/packages/plugin-react/src/fast-refresh.ts @@ -1,6 +1,6 @@ -import type { types as t } from '@babel/core' import fs from 'fs' import path from 'path' +import type { types as t } from '@babel/core' export const runtimePublicPath = '/@react-refresh' diff --git a/packages/plugin-react/src/index.ts b/packages/plugin-react/src/index.ts index cefab59d94fe53..4ca3e0d371f6c9 100644 --- a/packages/plugin-react/src/index.ts +++ b/packages/plugin-react/src/index.ts @@ -38,15 +38,10 @@ export interface Options { * @default true */ jsxPure?: boolean - /** * Babel configuration applied in both dev and prod. */ babel?: BabelOptions - /** - * @deprecated Use `babel.parserOpts.plugins` instead - */ - parserPlugins?: ParserOptions['plugins'] } export type BabelOptions = Omit< @@ -104,7 +99,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] { babelOptions.presets ||= [] babelOptions.overrides ||= [] babelOptions.parserOpts ||= {} as any - babelOptions.parserOpts.plugins ||= opts.parserPlugins || [] + babelOptions.parserOpts.plugins ||= [] // Support patterns like: // - import * as React from 'react'; diff --git a/packages/plugin-react/src/jsx-runtime/babel-import-to-require.ts b/packages/plugin-react/src/jsx-runtime/babel-import-to-require.ts index dc7129862fd976..01e4cc4c37d478 100644 --- a/packages/plugin-react/src/jsx-runtime/babel-import-to-require.ts +++ b/packages/plugin-react/src/jsx-runtime/babel-import-to-require.ts @@ -1,5 +1,5 @@ import type * as babelCore from '@babel/core' -import type { types as t, Visitor } from '@babel/core' +import type { Visitor, types as t } from '@babel/core' /** * Replace this: diff --git a/packages/plugin-react/src/jsx-runtime/babel-restore-jsx.spec.ts b/packages/plugin-react/src/jsx-runtime/babel-restore-jsx.spec.ts index 59d6661bedd11b..b37ef698e5f215 100644 --- a/packages/plugin-react/src/jsx-runtime/babel-restore-jsx.spec.ts +++ b/packages/plugin-react/src/jsx-runtime/babel-restore-jsx.spec.ts @@ -1,5 +1,6 @@ -import babelRestoreJSX from './babel-restore-jsx' import * as babel from '@babel/core' +import { describe, expect, it } from 'vitest' +import babelRestoreJSX from './babel-restore-jsx' function jsx(code: string) { return babel.transform(code, { diff --git a/packages/plugin-react/src/jsx-runtime/restore-jsx.spec.ts b/packages/plugin-react/src/jsx-runtime/restore-jsx.spec.ts new file mode 100644 index 00000000000000..fcad0f78c3373b --- /dev/null +++ b/packages/plugin-react/src/jsx-runtime/restore-jsx.spec.ts @@ -0,0 +1,56 @@ +import * as babel from '@babel/core' +import { describe, expect, it } from 'vitest' +import { restoreJSX } from './restore-jsx' + +async function jsx(sourceCode: string) { + const [ast] = await restoreJSX(babel, sourceCode, 'test.js') + if (ast == null) { + return ast + } + const { code } = await babel.transformFromAstAsync(ast, null, { + configFile: false + }) + return code +} +// jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; +// React__default.createElement(Foo)`) +// Tests adapted from: https://github.com/flying-sheep/babel-plugin-transform-react-createelement-to-jsx/blob/63137b6/test/index.js +describe('restore-jsx', () => { + it('should trans to ', async () => { + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(foo)`) + ).toBeNull() + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement("h1")`) + ).toMatch(`

;`) + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(Foo)`) + ).toMatch(`;`) + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(Foo.Bar)`) + ).toMatch(`;`) + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(Foo.Bar.Baz)`) + ).toMatch(`;`) + }) + + it('should handle props', async () => { + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(foo, {hi: there})`) + ).toBeNull() + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement("h1", {hi: there})`) + ).toMatch(`

;`) + expect( + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; + React__default.createElement(Foo, {hi: there})`) + ).toMatch(`;`) + }) +}) diff --git a/packages/plugin-react/src/jsx-runtime/restore-jsx.ts b/packages/plugin-react/src/jsx-runtime/restore-jsx.ts index 268153f4ba5d45..dbc2218d2343ff 100644 --- a/packages/plugin-react/src/jsx-runtime/restore-jsx.ts +++ b/packages/plugin-react/src/jsx-runtime/restore-jsx.ts @@ -20,32 +20,42 @@ export async function restoreJSX( } const [reactAlias, isCommonJS] = parseReactAlias(code) + if (!reactAlias) { return jsxNotFound } - const reactJsxRE = new RegExp( - '\\b' + reactAlias + '\\.(createElement|Fragment)\\b', - 'g' - ) - let hasCompiledJsx = false - code = code.replace(reactJsxRE, (_, prop) => { - hasCompiledJsx = true - // Replace with "React" so JSX can be reverse compiled. - return 'React.' + prop - }) + + const fragmentPattern = `\\b${reactAlias}\\.Fragment\\b` + const createElementPattern = `\\b${reactAlias}\\.createElement\\(\\s*([A-Z"'][\\w$.]*["']?)` + + // Replace the alias with "React" so JSX can be reverse compiled. + code = code + .replace(new RegExp(fragmentPattern, 'g'), () => { + hasCompiledJsx = true + return 'React.Fragment' + }) + .replace(new RegExp(createElementPattern, 'g'), (original, component) => { + if (/^[a-z][\w$]*$/.test(component)) { + // Take care not to replace the alias for `createElement` calls whose + // component is a lowercased variable, since the `restoreJSX` Babel + // plugin leaves them untouched. + return original + } + hasCompiledJsx = true + return ( + 'React.createElement(' + + // Assume `Fragment` is equivalent to `React.Fragment` so modules + // that use `import {Fragment} from 'react'` are reverse compiled. + (component === 'Fragment' ? 'React.Fragment' : component) + ) + }) if (!hasCompiledJsx) { return jsxNotFound } - // Support modules that use `import {Fragment} from 'react'` - code = code.replace( - /createElement\(Fragment,/g, - 'createElement(React.Fragment,' - ) - babelRestoreJSX ||= import('./babel-restore-jsx') const result = await babel.transformAsync(code, { diff --git a/packages/plugin-vue-jsx/index.js b/packages/plugin-vue-jsx/index.js index 248270765d19a1..929f4fb44cd434 100644 --- a/packages/plugin-vue-jsx/index.js +++ b/packages/plugin-vue-jsx/index.js @@ -48,12 +48,6 @@ function vueJsxPlugin(options = {}) { name: 'vite:vue-jsx', config(config) { - const optionsApi = config.define - ? config.define.__VUE_OPTIONS_API__ - : undefined - const devTools = config.define - ? config.define.__VUE_PROD_DEVTOOLS__ - : undefined return { // only apply esbuild to ts files // since we are handling jsx and tsx now @@ -61,8 +55,8 @@ function vueJsxPlugin(options = {}) { include: /\.ts$/ }, define: { - __VUE_OPTIONS_API__: optionsApi != null ? optionsApi : true, - __VUE_PROD_DEVTOOLS__: devTools != null ? devTools : false + __VUE_OPTIONS_API__: config.define?.__VUE_OPTIONS_API__ ?? true, + __VUE_PROD_DEVTOOLS__: config.define?.__VUE_PROD_DEVTOOLS__ ?? false } } }, diff --git a/packages/plugin-vue-jsx/package.json b/packages/plugin-vue-jsx/package.json index 487d207a0df24d..11e83bac3321b6 100644 --- a/packages/plugin-vue-jsx/package.json +++ b/packages/plugin-vue-jsx/package.json @@ -10,7 +10,7 @@ "main": "index.js", "types": "index.d.ts", "engines": { - "node": ">=12.0.0" + "node": ">=14.6.0" }, "repository": { "type": "git", @@ -22,11 +22,15 @@ }, "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx#readme", "dependencies": { - "@babel/core": "^7.17.9", + "@babel/core": "^7.17.10", "@babel/plugin-syntax-import-meta": "^7.10.4", "@babel/plugin-transform-typescript": "^7.16.8", "@rollup/pluginutils": "^4.2.1", "@vue/babel-plugin-jsx": "^1.1.1", "hash-sum": "^2.0.0" + }, + "peerDependencies": { + "vite": "^2.0.0", + "vue": "^3.0.0" } } diff --git a/packages/plugin-vue/CHANGELOG.md b/packages/plugin-vue/CHANGELOG.md index 135daffbfaaa67..4990d5fc10bd50 100644 --- a/packages/plugin-vue/CHANGELOG.md +++ b/packages/plugin-vue/CHANGELOG.md @@ -1,3 +1,11 @@ +## 2.3.2 (2022-05-04) + +* feat: import ts with .js in vue (#7998) ([9974094](https://github.com/vitejs/vite/commit/9974094)), closes [#7998](https://github.com/vitejs/vite/issues/7998) +* refactor(plugin-vue): remove querystring import (#7997) ([f3d15f1](https://github.com/vitejs/vite/commit/f3d15f1)), closes [#7997](https://github.com/vitejs/vite/issues/7997) +* chore(deps): update all non-major dependencies (#7780) ([eba9d05](https://github.com/vitejs/vite/commit/eba9d05)), closes [#7780](https://github.com/vitejs/vite/issues/7780) + + + ## 2.3.1 (2022-03-30) * chore(plugin-vue): revert #7527, lower vite peer dep ([447bbeb](https://github.com/vitejs/vite/commit/447bbeb)), closes [#7527](https://github.com/vitejs/vite/issues/7527) diff --git a/packages/plugin-vue/package.json b/packages/plugin-vue/package.json index 9f401ac7fa86b1..5ee997fe4c05d0 100644 --- a/packages/plugin-vue/package.json +++ b/packages/plugin-vue/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-vue", - "version": "2.3.1", + "version": "2.3.2", "license": "MIT", "author": "Evan You", "files": [ @@ -19,7 +19,7 @@ "prepublishOnly": "(cd ../vite && npm run build) && npm run build" }, "engines": { - "node": ">=12.0.0" + "node": ">=14.6.0" }, "repository": { "type": "git", @@ -36,10 +36,9 @@ }, "devDependencies": { "@rollup/pluginutils": "^4.2.1", - "@types/hash-sum": "^1.0.0", "debug": "^4.3.4", "hash-sum": "^2.0.0", - "rollup": "^2.59.0", + "rollup": "^2.72.1", "slash": "^4.0.0", "source-map": "^0.6.1", "vue": "^3.2.33" diff --git a/packages/plugin-vue/src/handleHotUpdate.ts b/packages/plugin-vue/src/handleHotUpdate.ts index 7c2a7ef7ee2f1f..fbf7d2c1f5d490 100644 --- a/packages/plugin-vue/src/handleHotUpdate.ts +++ b/packages/plugin-vue/src/handleHotUpdate.ts @@ -1,12 +1,12 @@ import _debug from 'debug' import type { SFCBlock, SFCDescriptor } from 'vue/compiler-sfc' +import type { HmrContext, ModuleNode } from 'vite' import { createDescriptor, getDescriptor, setPrevDescriptor } from './utils/descriptorCache' import { getResolvedScript, setResolvedScript } from './script' -import type { ModuleNode, HmrContext } from 'vite' import type { ResolvedOptions } from '.' const debug = _debug('vite:hmr') diff --git a/packages/plugin-vue/src/main.ts b/packages/plugin-vue/src/main.ts index 44b1de74721efd..6df6901a2bab40 100644 --- a/packages/plugin-vue/src/main.ts +++ b/packages/plugin-vue/src/main.ts @@ -1,22 +1,21 @@ -import qs from 'querystring' import path from 'path' import type { SFCBlock, SFCDescriptor } from 'vue/compiler-sfc' -import type { ResolvedOptions } from '.' +import type { PluginContext, SourceMap, TransformPluginContext } from 'rollup' +import { normalizePath } from '@rollup/pluginutils' +import type { RawSourceMap } from 'source-map' +import { SourceMapConsumer, SourceMapGenerator } from 'source-map' +import { transformWithEsbuild } from 'vite' import { createDescriptor, getPrevDescriptor, setSrcDescriptor } from './utils/descriptorCache' -import type { PluginContext, SourceMap, TransformPluginContext } from 'rollup' -import { normalizePath } from '@rollup/pluginutils' -import { resolveScript, isUseInlineTemplate } from './script' +import { isUseInlineTemplate, resolveScript } from './script' import { transformTemplateInMain } from './template' -import { isOnlyTemplateChanged, isEqualBlock } from './handleHotUpdate' -import type { RawSourceMap } from 'source-map' -import { SourceMapConsumer, SourceMapGenerator } from 'source-map' +import { isEqualBlock, isOnlyTemplateChanged } from './handleHotUpdate' import { createRollupError } from './utils/error' -import { transformWithEsbuild } from 'vite' import { EXPORT_HELPER_ID } from './helper' +import type { ResolvedOptions } from '.' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export async function transformMain( @@ -212,6 +211,11 @@ export async function transformMain( code: resolvedCode, map: resolvedMap || { mappings: '' + }, + meta: { + vite: { + lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || 'js' + } } } } @@ -223,6 +227,7 @@ async function genTemplateCode( ssr: boolean ) { const template = descriptor.template! + const hasScoped = descriptor.styles.some((style) => style.scoped) // If the template is not using pre-processor AND is not using external src, // compile and inline it directly in the main module. When served in vite this @@ -237,12 +242,22 @@ async function genTemplateCode( ) } else { if (template.src) { - await linkSrcToDescriptor(template.src, descriptor, pluginContext) + await linkSrcToDescriptor( + template.src, + descriptor, + pluginContext, + hasScoped + ) } const src = template.src || descriptor.filename - const srcQuery = template.src ? `&src=${descriptor.id}` : `` + const srcQuery = template.src + ? hasScoped + ? `&src=${descriptor.id}` + : '&src=true' + : '' + const scopedQuery = hasScoped ? `&scoped=true` : `` const attrsQuery = attrsToQuery(template.attrs, 'js', true) - const query = `?vue&type=template${srcQuery}${attrsQuery}` + const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}` const request = JSON.stringify(src + query) const renderFnName = ssr ? 'ssrRender' : 'render' return { @@ -268,7 +283,10 @@ async function genScriptCode( if (script) { // If the script is js/ts and has no external src, it can be directly placed // in the main module. - if ((!script.lang || script.lang === 'ts') && !script.src) { + if ( + (!script.lang || (script.lang === 'ts' && options.devServer)) && + !script.src + ) { scriptCode = options.compiler.rewriteDefault( script.content, '_sfc_main', @@ -277,12 +295,12 @@ async function genScriptCode( map = script.map } else { if (script.src) { - await linkSrcToDescriptor(script.src, descriptor, pluginContext) + await linkSrcToDescriptor(script.src, descriptor, pluginContext, false) } const src = script.src || descriptor.filename const langFallback = (script.src && path.extname(src).slice(1)) || 'js' const attrsQuery = attrsToQuery(script.attrs, langFallback) - const srcQuery = script.src ? `&src=${descriptor.id}` : `` + const srcQuery = script.src ? `&src=true` : `` const query = `?vue&type=script${srcQuery}${attrsQuery}` const request = JSON.stringify(src + query) scriptCode = @@ -307,13 +325,22 @@ async function genStyleCode( for (let i = 0; i < descriptor.styles.length; i++) { const style = descriptor.styles[i] if (style.src) { - await linkSrcToDescriptor(style.src, descriptor, pluginContext) + await linkSrcToDescriptor( + style.src, + descriptor, + pluginContext, + style.scoped + ) } const src = style.src || descriptor.filename // do not include module in default query, since we use it to indicate // that the module needs to export the modules json const attrsQuery = attrsToQuery(style.attrs, 'css') - const srcQuery = style.src ? `&src=${descriptor.id}` : `` + const srcQuery = style.src + ? style.scoped + ? `&src=${descriptor.id}` + : '&src=true' + : '' const directQuery = asCustomElement ? `&inline` : `` const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}` const styleRequest = src + query + attrsQuery @@ -383,11 +410,11 @@ async function genCustomBlockCode( for (let index = 0; index < descriptor.customBlocks.length; index++) { const block = descriptor.customBlocks[index] if (block.src) { - await linkSrcToDescriptor(block.src, descriptor, pluginContext) + await linkSrcToDescriptor(block.src, descriptor, pluginContext, false) } const src = block.src || descriptor.filename const attrsQuery = attrsToQuery(block.attrs, block.type) - const srcQuery = block.src ? `&src` : `` + const srcQuery = block.src ? `&src=true` : `` const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}` const request = JSON.stringify(src + query) code += `import block${index} from ${request}\n` @@ -404,13 +431,14 @@ async function genCustomBlockCode( async function linkSrcToDescriptor( src: string, descriptor: SFCDescriptor, - pluginContext: PluginContext + pluginContext: PluginContext, + scoped?: boolean ) { const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src // #1812 if the src points to a dep file, the resolved id may contain a // version query. - setSrcDescriptor(srcFile.replace(/\?.*$/, ''), descriptor) + setSrcDescriptor(srcFile.replace(/\?.*$/, ''), descriptor, scoped) } // these are built-in query parameters so should be ignored @@ -426,8 +454,8 @@ function attrsToQuery( for (const name in attrs) { const value = attrs[name] if (!ignoreList.includes(name)) { - query += `&${qs.escape(name)}${ - value ? `=${qs.escape(String(value))}` : `` + query += `&${encodeURIComponent(name)}${ + value ? `=${encodeURIComponent(value)}` : `` }` } } diff --git a/packages/plugin-vue/src/script.ts b/packages/plugin-vue/src/script.ts index 93610dcf7f6a36..f5d488c22c279a 100644 --- a/packages/plugin-vue/src/script.ts +++ b/packages/plugin-vue/src/script.ts @@ -1,6 +1,6 @@ import type { SFCDescriptor, SFCScriptBlock } from 'vue/compiler-sfc' -import type { ResolvedOptions } from '.' import { resolveTemplateCompilerOptions } from './template' +import type { ResolvedOptions } from '.' // ssr and non ssr builds would output different script content const clientCache = new WeakMap() diff --git a/packages/plugin-vue/src/style.ts b/packages/plugin-vue/src/style.ts index cab75791bd54ec..aa124de17b8894 100644 --- a/packages/plugin-vue/src/style.ts +++ b/packages/plugin-vue/src/style.ts @@ -1,8 +1,8 @@ import type { SFCDescriptor } from 'vue/compiler-sfc' import type { ExistingRawSourceMap, TransformPluginContext } from 'rollup' -import type { ResolvedOptions } from '.' import type { RawSourceMap } from 'source-map' import { formatPostcssSourceMap } from 'vite' +import type { ResolvedOptions } from '.' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export async function transformStyle( diff --git a/packages/plugin-vue/src/template.ts b/packages/plugin-vue/src/template.ts index 72e9588967556e..5ff2fb399829f2 100644 --- a/packages/plugin-vue/src/template.ts +++ b/packages/plugin-vue/src/template.ts @@ -1,15 +1,15 @@ import path from 'path' import slash from 'slash' import type { + CompilerOptions, SFCDescriptor, SFCTemplateCompileOptions, - SFCTemplateCompileResults, - CompilerOptions + SFCTemplateCompileResults } from 'vue/compiler-sfc' import type { PluginContext, TransformPluginContext } from 'rollup' -import type { ResolvedOptions } from '.' import { getResolvedScript } from './script' import { createRollupError } from './utils/error' +import type { ResolvedOptions } from '.' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export async function transformTemplateAsModule( @@ -123,7 +123,7 @@ export function resolveTemplateCompilerOptions( slash(path.relative(options.root, path.dirname(filename))) } } - } else { + } else if (transformAssetUrls !== false) { // build: force all asset urls into import requests so that they go through // the assets plugin for asset registration assetUrlOptions = { @@ -139,7 +139,7 @@ export function resolveTemplateCompilerOptions( tags: transformAssetUrls as any } } else { - transformAssetUrls = { ...transformAssetUrls, ...assetUrlOptions } + transformAssetUrls = { ...assetUrlOptions, ...transformAssetUrls } } } else { transformAssetUrls = assetUrlOptions diff --git a/packages/plugin-vue/src/utils/descriptorCache.ts b/packages/plugin-vue/src/utils/descriptorCache.ts index c0b77e72d3e613..5143a6131d5ddc 100644 --- a/packages/plugin-vue/src/utils/descriptorCache.ts +++ b/packages/plugin-vue/src/utils/descriptorCache.ts @@ -69,11 +69,22 @@ export function getSrcDescriptor( filename: string, query: VueQuery ): SFCDescriptor { - return cache.get(`${filename}?src=${query.src}`)! + if (query.scoped) { + return cache.get(`${filename}?src=${query.src}`)! + } + return cache.get(filename)! } -export function setSrcDescriptor(filename: string, entry: SFCDescriptor): void { - // if multiple Vue files use the same src file, they will be overwritten - // should use other key - cache.set(`${filename}?src=${entry.id}`, entry) +export function setSrcDescriptor( + filename: string, + entry: SFCDescriptor, + scoped?: boolean +): void { + if (scoped) { + // if multiple Vue files use the same src file, they will be overwritten + // should use other key + cache.set(`${filename}?src=${entry.id}`, entry) + return + } + cache.set(filename, entry) } diff --git a/packages/plugin-vue/src/utils/query.ts b/packages/plugin-vue/src/utils/query.ts index d41cb1be2cf536..f579067e52f8d8 100644 --- a/packages/plugin-vue/src/utils/query.ts +++ b/packages/plugin-vue/src/utils/query.ts @@ -1,5 +1,3 @@ -import qs from 'querystring' - export interface VueQuery { vue?: boolean src?: string @@ -7,6 +5,7 @@ export interface VueQuery { index?: number lang?: string raw?: boolean + scoped?: boolean } export function parseVueRequest(id: string): { @@ -14,7 +13,7 @@ export function parseVueRequest(id: string): { query: VueQuery } { const [filename, rawQuery] = id.split(`?`, 2) - const query = qs.parse(rawQuery) as VueQuery + const query = Object.fromEntries(new URLSearchParams(rawQuery)) as VueQuery if (query.vue != null) { query.vue = true } @@ -24,6 +23,9 @@ export function parseVueRequest(id: string): { if (query.raw != null) { query.raw = true } + if (query.scoped != null) { + query.scoped = true + } return { filename, query diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index c2dc1488d84b21..3c967f289c1f34 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,36 @@ +## 2.9.8 (2022-05-04) + +* fix: inline js and css paths for virtual html (#7993) ([d49e3fb](https://github.com/vitejs/vite/commit/d49e3fb)), closes [#7993](https://github.com/vitejs/vite/issues/7993) +* fix: only handle merge ssr.noExternal (#8003) ([642d65b](https://github.com/vitejs/vite/commit/642d65b)), closes [#8003](https://github.com/vitejs/vite/issues/8003) +* fix: optimized processing folder renaming in win (fix #7939) (#8019) ([e5fe1c6](https://github.com/vitejs/vite/commit/e5fe1c6)), closes [#7939](https://github.com/vitejs/vite/issues/7939) [#8019](https://github.com/vitejs/vite/issues/8019) +* fix(css): do not clean id when passing to postcss (fix #7822) (#7827) ([72f17f8](https://github.com/vitejs/vite/commit/72f17f8)), closes [#7822](https://github.com/vitejs/vite/issues/7822) [#7827](https://github.com/vitejs/vite/issues/7827) +* fix(css): var in image-set (#7921) ([e96b908](https://github.com/vitejs/vite/commit/e96b908)), closes [#7921](https://github.com/vitejs/vite/issues/7921) +* fix(ssr): allow ssrTransform to parse hashbang (#8005) ([6420ba0](https://github.com/vitejs/vite/commit/6420ba0)), closes [#8005](https://github.com/vitejs/vite/issues/8005) +* feat: import ts with .js in vue (#7998) ([9974094](https://github.com/vitejs/vite/commit/9974094)), closes [#7998](https://github.com/vitejs/vite/issues/7998) +* chore: remove maybeVirtualHtmlSet (#8010) ([e85164e](https://github.com/vitejs/vite/commit/e85164e)), closes [#8010](https://github.com/vitejs/vite/issues/8010) + + + +## 2.9.7 (2022-05-02) + +* chore: update license ([d58c030](https://github.com/vitejs/vite/commit/d58c030)) +* chore(css): catch postcss config error (fix #2793) (#7934) ([7f535ac](https://github.com/vitejs/vite/commit/7f535ac)), closes [#2793](https://github.com/vitejs/vite/issues/2793) [#7934](https://github.com/vitejs/vite/issues/7934) +* chore(deps): update all non-major dependencies (#7949) ([b877d30](https://github.com/vitejs/vite/commit/b877d30)), closes [#7949](https://github.com/vitejs/vite/issues/7949) +* fix: inject esbuild helpers in IIFE and UMD wrappers (#7948) ([f7d2d71](https://github.com/vitejs/vite/commit/f7d2d71)), closes [#7948](https://github.com/vitejs/vite/issues/7948) +* fix: inline css hash (#7974) ([f6ae60d](https://github.com/vitejs/vite/commit/f6ae60d)), closes [#7974](https://github.com/vitejs/vite/issues/7974) +* fix: inline style hmr, transform style code inplace (#7869) ([a30a548](https://github.com/vitejs/vite/commit/a30a548)), closes [#7869](https://github.com/vitejs/vite/issues/7869) +* fix: use NODE_ENV in optimizer (#7673) ([50672e4](https://github.com/vitejs/vite/commit/50672e4)), closes [#7673](https://github.com/vitejs/vite/issues/7673) +* fix(css): clean comments before hoist at rules (#7924) ([e48827f](https://github.com/vitejs/vite/commit/e48827f)), closes [#7924](https://github.com/vitejs/vite/issues/7924) +* fix(css): dynamic import css in package fetches removed js (fixes #7955, #6823) (#7969) ([025eebf](https://github.com/vitejs/vite/commit/025eebf)), closes [#7955](https://github.com/vitejs/vite/issues/7955) [#6823](https://github.com/vitejs/vite/issues/6823) [#7969](https://github.com/vitejs/vite/issues/7969) +* fix(css): inline css module when ssr, minify issue (fix #5471) (#7807) ([cf8a48a](https://github.com/vitejs/vite/commit/cf8a48a)), closes [#5471](https://github.com/vitejs/vite/issues/5471) [#7807](https://github.com/vitejs/vite/issues/7807) +* fix(css): sourcemap crash with postcss (#7982) ([7f9f8f1](https://github.com/vitejs/vite/commit/7f9f8f1)), closes [#7982](https://github.com/vitejs/vite/issues/7982) +* fix(css): support postcss.config.ts (#7935) ([274c10e](https://github.com/vitejs/vite/commit/274c10e)), closes [#7935](https://github.com/vitejs/vite/issues/7935) +* fix(ssr): failed ssrLoadModule call throws same error (#7177) ([891e7fc](https://github.com/vitejs/vite/commit/891e7fc)), closes [#7177](https://github.com/vitejs/vite/issues/7177) +* fix(worker): import.meta.* (#7706) ([b092697](https://github.com/vitejs/vite/commit/b092697)), closes [#7706](https://github.com/vitejs/vite/issues/7706) +* docs: `server.origin` config trailing slash (fix #6622) (#7865) ([5c1ee5a](https://github.com/vitejs/vite/commit/5c1ee5a)), closes [#6622](https://github.com/vitejs/vite/issues/6622) [#7865](https://github.com/vitejs/vite/issues/7865) + + + ## 2.9.6 (2022-04-26) * fix: `apply` condition skipped for nested plugins (#7741) ([1f2ca53](https://github.com/vitejs/vite/commit/1f2ca53)), closes [#7741](https://github.com/vitejs/vite/issues/7741) diff --git a/packages/vite/LICENSE.md b/packages/vite/LICENSE.md index ccff3f1508a73b..2b43883f1b2b67 100644 --- a/packages/vite/LICENSE.md +++ b/packages/vite/LICENSE.md @@ -237,6 +237,33 @@ Repository: git+https://github.com/ampproject/remapping.git --------------------------------------- +## @jridgewell/gen-mapping +License: MIT +By: Justin Ridgewell +Repository: https://github.com/jridgewell/gen-mapping + +> Copyright 2022 Justin Ridgewell +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + ## @jridgewell/resolve-uri License: MIT By: Justin Ridgewell @@ -264,6 +291,33 @@ Repository: https://github.com/jridgewell/resolve-uri --------------------------------------- +## @jridgewell/set-array +License: MIT +By: Justin Ridgewell +Repository: https://github.com/jridgewell/set-array + +> Copyright 2022 Justin Ridgewell +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + ## @jridgewell/sourcemap-codec License: MIT By: Rich Harris @@ -577,7 +631,7 @@ Repository: https://github.com/acornjs/acorn.git > MIT License > -> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> Copyright (C) 2012-2022 by various contributors (see AUTHORS) > > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal @@ -3411,6 +3465,35 @@ Repository: chalk/strip-ansi --------------------------------------- +## strip-literal +License: MIT +By: Anthony Fu +Repository: git+https://github.com/antfu/strip-literal.git + +> MIT License +> +> Copyright (c) 2022 Anthony Fu +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + ## to-regex-range License: MIT By: Jon Schlinkert, Rouven Weßling @@ -3523,6 +3606,34 @@ Repository: git+https://github.com/dominikg/tsconfck.git --------------------------------------- +## ufo +License: MIT +Repository: unjs/ufo + +> MIT License +> +> Copyright (c) 2020 Nuxt Contrib +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + ## unpipe License: MIT By: Douglas Christopher Wilson diff --git a/packages/vite/client.d.ts b/packages/vite/client.d.ts index aaac1ea986251d..af8e6a6f9d1494 100644 --- a/packages/vite/client.d.ts +++ b/packages/vite/client.d.ts @@ -1,4 +1,3 @@ -/// /// // CSS modules diff --git a/packages/vite/package.json b/packages/vite/package.json index b2caecf4e228ca..a80087dafafbc2 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.6", + "version": "2.9.8", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", @@ -17,7 +17,7 @@ "types" ], "engines": { - "node": ">=12.2.0" + "node": ">=14.6.0" }, "repository": { "type": "git", @@ -43,19 +43,19 @@ }, "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!", "dependencies": { - "esbuild": "^0.14.27", - "postcss": "^8.4.12", + "esbuild": "^0.14.38", + "postcss": "^8.4.13", "resolve": "^1.22.0", - "rollup": "^2.59.0" + "rollup": "^2.72.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "devDependencies": { - "@ampproject/remapping": "^2.1.2", - "@babel/parser": "^7.17.9", - "@babel/types": "^7.17.0", - "@jridgewell/trace-mapping": "^0.3.9", + "@ampproject/remapping": "^2.2.0", + "@babel/parser": "^7.17.10", + "@babel/types": "^7.17.10", + "@jridgewell/trace-mapping": "^0.3.10", "@rollup/plugin-alias": "^3.1.9", "@rollup/plugin-commonjs": "^21.1.0", "@rollup/plugin-dynamic-import-vars": "^1.4.3", @@ -63,21 +63,8 @@ "@rollup/plugin-node-resolve": "13.2.1", "@rollup/plugin-typescript": "^8.3.2", "@rollup/pluginutils": "^4.2.1", - "@types/convert-source-map": "^1.5.2", - "@types/cross-spawn": "^6.0.2", - "@types/debug": "^4.1.7", - "@types/estree": "^0.0.51", - "@types/etag": "^1.8.1", - "@types/less": "^3.0.3", - "@types/micromatch": "^4.0.2", - "@types/mime": "^2.0.3", - "@types/node": "^17.0.25", - "@types/resolve": "^1.20.1", - "@types/sass": "~1.43.1", - "@types/stylus": "^0.48.37", - "@types/ws": "^8.5.3", "@vue/compiler-dom": "^3.2.33", - "acorn": "^8.7.0", + "acorn": "^8.7.1", "cac": "6.7.9", "chokidar": "^3.5.3", "connect": "^3.7.0", @@ -112,11 +99,13 @@ "source-map-js": "^1.0.2", "source-map-support": "^0.5.21", "strip-ansi": "^6.0.1", - "terser": "^5.12.1", + "strip-literal": "^0.3.0", + "terser": "^5.13.1", "tsconfck": "^1.2.2", - "tslib": "^2.3.1", + "tslib": "^2.4.0", "types": "link:./types", - "ws": "^8.5.0" + "ufo": "^0.8.4", + "ws": "^8.6.0" }, "peerDependencies": { "less": "*", diff --git a/packages/vite/rollup.config.js b/packages/vite/rollup.config.js index 31ab56cd07e02e..93f4f33bdec398 100644 --- a/packages/vite/rollup.config.js +++ b/packages/vite/rollup.config.js @@ -171,6 +171,11 @@ const createNodeConfig = (isProduction) => { 'lilconfig/dist/index.js': { pattern: /: require,/g, replacement: `: eval('require'),` + }, + // postcss-load-config calls require after register ts-node + 'postcss-load-config/src/index.js': { + src: `require(configFile)`, + replacement: `eval('require')(configFile)` } }), commonjs({ diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 420d084ef9a981..6a7f9b27c3a700 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -106,6 +106,7 @@ async function handleMessage(payload: HMRPayload) { const payloadPath = base + payload.path.slice(1) if ( pagePath === payloadPath || + payload.path === '/index.html' || (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath) ) { location.reload() @@ -200,12 +201,10 @@ async function waitForSuccessfulPing(ms = 1000) { // eslint-disable-next-line no-constant-condition while (true) { try { - const pingResponse = await fetch(`${base}__vite_ping`) - - // success - 2xx status code - if (pingResponse.ok) break - // failure - non-2xx status code - else throw new Error() + // A fetch on a websocket URL will return a successful promise with status 400, + // but will reject a networking error. + await fetch(`${location.protocol}//${socketHost}`) + break } catch (e) { // wait ms before attempting to ping again await new Promise((resolve) => setTimeout(resolve, ms)) @@ -432,13 +431,6 @@ export function createHotContext(ownerPath: string): ViteHotContext { } }, - acceptDeps() { - throw new Error( - `hot.acceptDeps() is deprecated. ` + - `Use hot.accept() with the same signature instead.` - ) - }, - dispose(cb) { disposeMap.set(ownerPath, cb) }, diff --git a/packages/vite/src/node/__tests__/asset.spec.ts b/packages/vite/src/node/__tests__/asset.spec.ts index 6e6b969bcbd38c..a756cb12652739 100644 --- a/packages/vite/src/node/__tests__/asset.spec.ts +++ b/packages/vite/src/node/__tests__/asset.spec.ts @@ -1,3 +1,4 @@ +import { describe, expect, test } from 'vitest' import { assetFileNamesToFileName, getAssetHash } from '../plugins/asset' describe('getAssetHash', () => { diff --git a/packages/vite/src/node/__tests__/build.spec.ts b/packages/vite/src/node/__tests__/build.spec.ts index b3ef37e64fd28e..3b34851203e149 100644 --- a/packages/vite/src/node/__tests__/build.spec.ts +++ b/packages/vite/src/node/__tests__/build.spec.ts @@ -1,5 +1,13 @@ -import { resolveLibFilename } from '../build' import { resolve } from 'path' +import { describe, expect, test } from 'vitest' +import type { LibraryFormats, LibraryOptions } from '../build' +import { resolveLibFilename } from '../build' + +type FormatsToFileNames = [LibraryFormats, string][] +const baseLibOptions: LibraryOptions = { + fileName: 'my-lib', + entry: 'mylib.js' +} describe('resolveLibFilename', () => { test('custom filename function', () => { @@ -25,7 +33,7 @@ describe('resolveLibFilename', () => { resolve(__dirname, 'packages/name') ) - expect(filename).toBe('custom-filename.es.js') + expect(filename).toBe('custom-filename.es.mjs') }) test('package name as filename', () => { @@ -37,7 +45,7 @@ describe('resolveLibFilename', () => { resolve(__dirname, 'packages/name') ) - expect(filename).toBe('mylib.es.js') + expect(filename).toBe('mylib.es.mjs') }) test('custom filename and no package name', () => { @@ -50,7 +58,7 @@ describe('resolveLibFilename', () => { resolve(__dirname, 'packages/noname') ) - expect(filename).toBe('custom-filename.es.js') + expect(filename).toBe('custom-filename.es.mjs') }) test('missing filename', () => { @@ -64,4 +72,42 @@ describe('resolveLibFilename', () => { ) }).toThrow() }) + + test('commonjs package extensions', () => { + const formatsToFilenames: FormatsToFileNames = [ + ['es', 'my-lib.es.mjs'], + ['umd', 'my-lib.umd.js'], + ['cjs', 'my-lib.cjs.js'], + ['iife', 'my-lib.iife.js'] + ] + + for (const [format, expectedFilename] of formatsToFilenames) { + const filename = resolveLibFilename( + baseLibOptions, + format, + resolve(__dirname, 'packages/noname') + ) + + expect(filename).toBe(expectedFilename) + } + }) + + test('module package extensions', () => { + const formatsToFilenames: FormatsToFileNames = [ + ['es', 'my-lib.es.js'], + ['umd', 'my-lib.umd.cjs'], + ['cjs', 'my-lib.cjs.cjs'], + ['iife', 'my-lib.iife.js'] + ] + + for (const [format, expectedFilename] of formatsToFilenames) { + const filename = resolveLibFilename( + baseLibOptions, + format, + resolve(__dirname, 'packages/module') + ) + + expect(filename).toBe(expectedFilename) + } + }) }) diff --git a/packages/vite/src/node/__tests__/cleanString.spec.ts b/packages/vite/src/node/__tests__/cleanString.spec.ts deleted file mode 100644 index f307c4816b7cd3..00000000000000 --- a/packages/vite/src/node/__tests__/cleanString.spec.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { assetAttrsConfig } from './../plugins/html' -import { emptyString } from '../../node/cleanString' - -test('comments', () => { - expect( - emptyString(` - // comment1 // comment - // comment1 - /* coment2 */ - /* - // coment3 - */ - /* // coment3 */ - /* // coment3 */ // comment - // comment 4 /* comment 5 */ - `).trim() - ).toBe('') -}) - -test('strings', () => { - const clean = emptyString(` - // comment1 - const a = 'aaaa' - /* coment2 */ - const b = "bbbb" - /* - // coment3 - */ - /* // coment3 */ - // comment 4 /* comment 5 */ - `) - expect(clean).toMatch("const a = '\0\0\0\0'") - expect(clean).toMatch('const b = "\0\0\0\0"') -}) - -test('escape character', () => { - const clean = emptyString(` - '1\\'1' - "1\\"1" - "1\\"1\\"1" - "1\\'1'\\"1" - "1'1'" - "1'\\'1\\''\\"1\\"\\"" - '1"\\"1\\""\\"1\\"\\"' - '""1""' - '"""1"""' - '""""1""""' - "''1''" - "'''1'''" - "''''1''''" - `) - expect(clean).not.toMatch('1') -}) - -test('regexp affect', () => { - const clean = emptyString(` - /'/ - '1' - /"/ - "1" - `) - expect(clean).not.toMatch('1') -}) - -test('strings comment nested', () => { - expect( - emptyString(` - // comment 1 /* " */ - const a = "a //" - // comment 2 /* " */ - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - // comment 1 /* ' */ - const a = "a //" - // comment 2 /* ' */ - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - // comment 1 /* \` */ - const a = "a //" - // comment 2 /* \` */ - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - const a = "a //" - console.log("console") - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - const a = "a /*" - console.log("console") - const b = "b */" - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - const a = "a ' " - console.log("console") - const b = "b ' " - `) - ).toMatch('const a = "\0\0\0\0"') - - expect( - emptyString(` - const a = "a \` " - console.log("console") - const b = "b \` " - `) - ).toMatch('const a = "\0\0\0\0"') -}) - -test('find empty string flag in raw index', () => { - const str = ` - const a = "aaaaa" - const b = "bbbbb" - ` - const clean = emptyString(str) - expect(clean).toMatch('const a = "\0\0\0\0\0"') - expect(clean).toMatch('const b = "\0\0\0\0\0"') - - const aIndex = str.indexOf('const a = "aaaaa"') - const aStart = clean.indexOf('\0\0\0\0\0', aIndex) - expect(str.slice(aStart, aStart + 5)).toMatch('aaaaa') - - const bIndex = str.indexOf('const b = "bbbbb"') - const bStart = clean.indexOf('\0\0\0\0\0', bIndex) - expect(str.slice(bStart, bStart + 5)).toMatch('bbbbb') -}) - -test('template string nested', () => { - let str = '`aaaa`' - let res = '`\0\0\0\0`' - let clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aaaa` `aaaa`' - res = '`\0\0\0\0` `\0\0\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aa${a}aa`' - res = '`\0\0${a}\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aa${a + `a` + a}aa`' - res = '`\0\0${a + `\0` + a}\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aa${a + `a` + a}aa` `aa${a + `a` + a}aa`' - res = '`\0\0${a + `\0` + a}\0\0` `\0\0${a + `\0` + a}\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa`' - res = '`\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = - '`aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa` `aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa`' - res = - '`\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0` `\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0`' - clean = emptyString(str) - expect(clean).toMatch(res) - - str = '`aaaa' - res = '' - try { - clean = emptyString(str) - } catch {} - expect(clean).toMatch(res) - - str = - "" - res = `` - clean = emptyString(str) - expect(clean).toMatch(res) -}) diff --git a/packages/vite/src/node/__tests__/config.spec.ts b/packages/vite/src/node/__tests__/config.spec.ts index dd427c19433475..4eaeae2822a1e3 100644 --- a/packages/vite/src/node/__tests__/config.spec.ts +++ b/packages/vite/src/node/__tests__/config.spec.ts @@ -1,5 +1,6 @@ +import { describe, expect, test } from 'vitest' import type { InlineConfig } from '..' -import type { UserConfigExport, UserConfig } from '../config' +import type { UserConfig, UserConfigExport } from '../config' import { mergeConfig, resolveConfig, resolveEnvPrefix } from '../config' describe('mergeConfig', () => { @@ -157,51 +158,29 @@ describe('mergeConfig', () => { expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) }) -}) - -describe('resolveConfig', () => { - beforeAll(() => { - // silence deprecation warning - jest.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterAll(() => { - jest.clearAllMocks() - }) - - test('copies optimizeDeps.keepNames to esbuildOptions.keepNames', async () => { - const config: InlineConfig = { - optimizeDeps: { - keepNames: false + test('handles ssr.noExternal', () => { + const baseConfig = { + ssr: { + noExternal: true } } - expect(await resolveConfig(config, 'serve')).toMatchObject({ - optimizeDeps: { - esbuildOptions: { - keepNames: false - } + const newConfig = { + ssr: { + noExternal: ['foo'] } - }) - }) + } - test('uses esbuildOptions.keepNames if set', async () => { - const config: InlineConfig = { - optimizeDeps: { - keepNames: true, - esbuildOptions: { - keepNames: false - } + const mergedConfig = { + ssr: { + noExternal: true } } - expect(await resolveConfig(config, 'serve')).toMatchObject({ - optimizeDeps: { - esbuildOptions: { - keepNames: false - } - } - }) + // merging either ways, `ssr.noExternal: true` should take highest priority + expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) + expect(mergeConfig(newConfig, baseConfig)).toEqual(mergedConfig) }) }) diff --git a/packages/vite/src/node/__tests__/dev.spec.ts b/packages/vite/src/node/__tests__/dev.spec.ts index 3eefd7b4b903c1..3b3b3d14553da4 100644 --- a/packages/vite/src/node/__tests__/dev.spec.ts +++ b/packages/vite/src/node/__tests__/dev.spec.ts @@ -1,3 +1,4 @@ +import { describe, expect, test } from 'vitest' import { resolveConfig } from '..' describe('resolveBuildOptions in dev', () => { diff --git a/packages/vite/src/node/__tests__/packages/module/package.json b/packages/vite/src/node/__tests__/packages/module/package.json new file mode 100644 index 00000000000000..3dbc1ca591c055 --- /dev/null +++ b/packages/vite/src/node/__tests__/packages/module/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 078cec2e0f3d77..16a3cbcd8e59e0 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -1,7 +1,8 @@ -import { cssUrlRE, cssPlugin, hoistAtRules } from '../../plugins/css' -import { resolveConfig } from '../../config' import fs from 'fs' import path from 'path' +import { describe, expect, test, vi } from 'vitest' +import { resolveConfig } from '../../config' +import { cssPlugin, cssUrlRE, hoistAtRules } from '../../plugins/css' describe('search css url function', () => { test('some spaces before it', () => { @@ -69,9 +70,9 @@ describe('css path resolutions', () => { await buildStart.call({}) - const mockFs = jest + const mockFs = vi .spyOn(fs, 'readFile') - // @ts-ignore jest.spyOn not recognize overrided `fs.readFile` definition. + // @ts-ignore vi.spyOn not recognize override `fs.readFile` definition. .mockImplementationOnce((p, encoding, callback) => { expect(p).toBe(path.join(mockedProjectPath, mockedBarCssRelativePath)) expect(encoding).toBe('utf-8') @@ -155,10 +156,52 @@ describe('hoist @ rules', () => { }) test('hoist @import and @charset', async () => { - const css = `.foo{color:red;}@import "bla";@charset "utf-8";.bar{color:grren;}@import "baz";` + const css = `.foo{color:red;}@import "bla";@charset "utf-8";.bar{color:green;}@import "baz";` + const result = await hoistAtRules(css) + expect(result).toBe( + `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:green;}` + ) + }) + + test('dont hoist @import in comments', async () => { + const css = `.foo{color:red;}/* @import "bla"; */@import "bar";` + const result = await hoistAtRules(css) + expect(result).toBe(`@import "bar";.foo{color:red;}/* @import "bla"; */`) + }) + + test('dont hoist @charset in comments', async () => { + const css = `.foo{color:red;}/* @charset "utf-8"; */@charset "utf-8";` const result = await hoistAtRules(css) expect(result).toBe( - `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:grren;}` + `@charset "utf-8";.foo{color:red;}/* @charset "utf-8"; */` ) }) + + test('dont hoist @import and @charset in comments', async () => { + const css = ` +.foo{color:red;} +/* + @import "bla"; +*/ +@charset "utf-8"; +/* + @charset "utf-8"; + @import "bar"; +*/ +@import "baz";` + const result = await hoistAtRules(css) + expect(result).toMatchInlineSnapshot(` + "@charset \\"utf-8\\";@import \\"baz\\"; + .foo{color:red;} + /* + @import \\"bla\\"; + */ + + /* + @charset \\"utf-8\\"; + @import \\"bar\\"; + */ + " + `) + }) }) diff --git a/packages/vite/src/node/__tests__/plugins/define.spec.ts b/packages/vite/src/node/__tests__/plugins/define.spec.ts index 9a65f8f3a51cea..932560a749f24d 100644 --- a/packages/vite/src/node/__tests__/plugins/define.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/define.spec.ts @@ -1,3 +1,4 @@ +import { describe, expect, test } from 'vitest' import { definePlugin } from '../../plugins/define' import { resolveConfig } from '../../config' diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/__snapshots__/parse.test.ts.snap b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/__snapshots__/parse.test.ts.snap new file mode 100644 index 00000000000000..be73ec998bc834 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/__snapshots__/parse.test.ts.snap @@ -0,0 +1,13 @@ +// Vitest Snapshot v1 + +exports[`parse positives > ? in url 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mo?ds/*.js\\", {\\"as\\":\\"raw\\",\\"import\\":\\"*\\"})), \`./mo?ds/\${base ?? foo}.js\`)"`; + +exports[`parse positives > ? in variables 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\", {\\"as\\":\\"raw\\",\\"import\\":\\"*\\"})), \`./mods/\${base ?? foo}.js\`)"`; + +exports[`parse positives > alias path 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\")), \`./mods/\${base}.js\`)"`; + +exports[`parse positives > basic 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\")), \`./mods/\${base}.js\`)"`; + +exports[`parse positives > with query raw 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\", {\\"as\\":\\"raw\\",\\"import\\":\\"*\\"})), \`./mods/\${base}.js\`)"`; + +exports[`parse positives > with query url 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\")), \`./mods/\${base}.js\`)"`; diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hello.js b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hello.js new file mode 100644 index 00000000000000..67900ef0999962 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hello.js @@ -0,0 +1,3 @@ +export function hello() { + return 'hello' +} diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hi.js b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hi.js new file mode 100644 index 00000000000000..45d3506803b2b6 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/mods/hi.js @@ -0,0 +1,3 @@ +export function hi() { + return 'hi' +} diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts new file mode 100644 index 00000000000000..a0017d50ae6cd2 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts @@ -0,0 +1,38 @@ +import { resolve } from 'path' +import { describe, expect, it } from 'vitest' +import { transformDynamicImport } from '../../../plugins/dynamicImportVars' + +async function run(input: string) { + const { glob, rawPattern } = await transformDynamicImport( + input, + resolve(__dirname, 'index.js'), + (id) => id.replace('@', resolve(__dirname, './mods/')) + ) + return `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)` +} + +describe('parse positives', () => { + it('basic', async () => { + expect(await run('`./mods/${base}.js`')).toMatchSnapshot() + }) + + it('alias path', async () => { + expect(await run('`@/${base}.js`')).toMatchSnapshot() + }) + + it('with query raw', async () => { + expect(await run('`./mods/${base}.js?raw`')).toMatchSnapshot() + }) + + it('with query url', async () => { + expect(await run('`./mods/${base}.js?url`')).toMatchSnapshot() + }) + + it('? in variables', async () => { + expect(await run('`./mods/${base ?? foo}.js?raw`')).toMatchSnapshot() + }) + + it('? in url', async () => { + expect(await run('`./mo?ds/${base ?? foo}.js?raw`')).toMatchSnapshot() + }) +}) diff --git a/packages/vite/src/node/__tests__/plugins/import.spec.ts b/packages/vite/src/node/__tests__/plugins/import.spec.ts index f0341e81b50f3c..661f35902ab580 100644 --- a/packages/vite/src/node/__tests__/plugins/import.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/import.spec.ts @@ -1,3 +1,4 @@ +import { describe, expect, test } from 'vitest' import { transformCjsImport } from '../../plugins/importAnalysis' describe('transformCjsImport', () => { diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap b/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap new file mode 100644 index 00000000000000..61ff6eeb4d2fc7 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap @@ -0,0 +1,162 @@ +// Vitest Snapshot v1 + +exports[`fixture > transform 1`] = ` +"import * as __vite_glob_1_0 from \\"./modules/a.ts\\" +import * as __vite_glob_1_1 from \\"./modules/b.ts\\" +import * as __vite_glob_1_2 from \\"./modules/index.ts\\" +import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\" +import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\" +import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\" +import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\" +import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\" +import \\"../../../../../../types/importMeta\\"; +export const basic = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"), +\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\") +}); +export const basicEager = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_1_0, +\\"./modules/b.ts\\": __vite_glob_1_1, +\\"./modules/index.ts\\": __vite_glob_1_2 +}); +export const ignore = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\") +}); +export const namedEager = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_3_0, +\\"./modules/b.ts\\": __vite_glob_3_1, +\\"./modules/index.ts\\": __vite_glob_3_2 +}); +export const namedDefault = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\").then(m => m[\\"default\\"]), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\").then(m => m[\\"default\\"]), +\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\").then(m => m[\\"default\\"]) +}); +export const eagerAs = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_5_0, +\\"./modules/b.ts\\": __vite_glob_5_1 +}); +export const rawImportModule = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts?raw\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts?raw\\") +}); +export const excludeSelf = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts\\") +}); +export const customQueryString = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts?custom\\") +}); +export const customQueryObject = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts?foo=bar&raw=true\\") +}); +export const parent = Object.assign({ + +}); +export const rootMixedRelative = Object.assign({ +\\"/css.spec.ts\\": () => import(\\"../../css.spec.ts?url\\").then(m => m[\\"default\\"]), +\\"/define.spec.ts\\": () => import(\\"../../define.spec.ts?url\\").then(m => m[\\"default\\"]), +\\"/import.spec.ts\\": () => import(\\"../../import.spec.ts?url\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/a.ts\\": () => import(\\"../fixture-b/a.ts?url\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/b.ts\\": () => import(\\"../fixture-b/b.ts?url\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/index.ts\\": () => import(\\"../fixture-b/index.ts?url\\").then(m => m[\\"default\\"]) +}); +export const cleverCwd1 = Object.assign({ +\\"./node_modules/framework/pages/hello.page.js\\": () => import(\\"./node_modules/framework/pages/hello.page.js\\") +}); +export const cleverCwd2 = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"), +\\"../fixture-b/a.ts\\": () => import(\\"../fixture-b/a.ts\\"), +\\"../fixture-b/b.ts\\": () => import(\\"../fixture-b/b.ts\\") +}); +" +`; + +exports[`fixture > transform with restoreQueryExtension 1`] = ` +"import * as __vite_glob_1_0 from \\"./modules/a.ts\\" +import * as __vite_glob_1_1 from \\"./modules/b.ts\\" +import * as __vite_glob_1_2 from \\"./modules/index.ts\\" +import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\" +import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\" +import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\" +import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\" +import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\" +import \\"../../../../../../types/importMeta\\"; +export const basic = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"), +\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\") +}); +export const basicEager = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_1_0, +\\"./modules/b.ts\\": __vite_glob_1_1, +\\"./modules/index.ts\\": __vite_glob_1_2 +}); +export const ignore = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\") +}); +export const namedEager = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_3_0, +\\"./modules/b.ts\\": __vite_glob_3_1, +\\"./modules/index.ts\\": __vite_glob_3_2 +}); +export const namedDefault = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\").then(m => m[\\"default\\"]), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\").then(m => m[\\"default\\"]), +\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\").then(m => m[\\"default\\"]) +}); +export const eagerAs = Object.assign({ +\\"./modules/a.ts\\": __vite_glob_5_0, +\\"./modules/b.ts\\": __vite_glob_5_1 +}); +export const rawImportModule = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts?raw\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts?raw\\") +}); +export const excludeSelf = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts\\") +}); +export const customQueryString = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts?custom&lang.ts\\") +}); +export const customQueryObject = Object.assign({ +\\"./sibling.ts\\": () => import(\\"./sibling.ts?foo=bar&raw=true&lang.ts\\") +}); +export const parent = Object.assign({ + +}); +export const rootMixedRelative = Object.assign({ +\\"/css.spec.ts\\": () => import(\\"../../css.spec.ts?url&lang.ts\\").then(m => m[\\"default\\"]), +\\"/define.spec.ts\\": () => import(\\"../../define.spec.ts?url&lang.ts\\").then(m => m[\\"default\\"]), +\\"/import.spec.ts\\": () => import(\\"../../import.spec.ts?url&lang.ts\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/a.ts\\": () => import(\\"../fixture-b/a.ts?url&lang.ts\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/b.ts\\": () => import(\\"../fixture-b/b.ts?url&lang.ts\\").then(m => m[\\"default\\"]), +\\"/importGlob/fixture-b/index.ts\\": () => import(\\"../fixture-b/index.ts?url&lang.ts\\").then(m => m[\\"default\\"]) +}); +export const cleverCwd1 = Object.assign({ +\\"./node_modules/framework/pages/hello.page.js\\": () => import(\\"./node_modules/framework/pages/hello.page.js\\") +}); +export const cleverCwd2 = Object.assign({ +\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"), +\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"), +\\"../fixture-b/a.ts\\": () => import(\\"../fixture-b/a.ts\\"), +\\"../fixture-b/b.ts\\": () => import(\\"../fixture-b/b.ts\\") +}); +" +`; + +exports[`fixture > virtual modules 1`] = ` +"Object.assign({ +\\"/modules/a.ts\\": () => import(\\"/modules/a.ts\\"), +\\"/modules/b.ts\\": () => import(\\"/modules/b.ts\\"), +\\"/modules/index.ts\\": () => import(\\"/modules/index.ts\\") +}) +Object.assign({ +\\"/../fixture-b/a.ts\\": () => import(\\"/../fixture-b/a.ts\\"), +\\"/../fixture-b/b.ts\\": () => import(\\"/../fixture-b/b.ts\\"), +\\"/../fixture-b/index.ts\\": () => import(\\"/../fixture-b/index.ts\\") +})" +`; diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/.gitignore b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/.gitignore new file mode 100644 index 00000000000000..2b9b8877da603f --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/.gitignore @@ -0,0 +1 @@ +!/node_modules/ diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts new file mode 100644 index 00000000000000..4fed8828e5f418 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts @@ -0,0 +1,69 @@ +import '../../../../../../types/importMeta' + +/* eslint-disable @typescript-eslint/comma-dangle */ +export interface ModuleType { + name: string +} + +export const basic = import.meta.glob('./modules/*.ts') + +export const basicEager = import.meta.glob('./modules/*.ts', { + eager: true +}) + +export const ignore = import.meta.glob(['./modules/*.ts', '!**/index.ts']) + +export const namedEager = import.meta.glob('./modules/*.ts', { + eager: true, + import: 'name' +}) + +export const namedDefault = import.meta.glob('./modules/*.ts', { + import: 'default' +}) + +export const eagerAs = import.meta.glob( + ['./modules/*.ts', '!**/index.ts'], + { eager: true, as: 'raw' } +) + +export const rawImportModule = import.meta.glob( + ['./modules/*.ts', '!**/index.ts'], + { as: 'raw', import: '*' } +) + +export const excludeSelf = import.meta.glob( + './*.ts' + // for test: annotation contain ")" + /* + * for test: annotation contain ")" + * */ +) + +export const customQueryString = import.meta.glob('./*.ts', { query: 'custom' }) + +export const customQueryObject = import.meta.glob('./*.ts', { + query: { + foo: 'bar', + raw: true + } +}) + +export const parent = import.meta.glob('../../playground/src/*.ts', { + as: 'url' +}) + +export const rootMixedRelative = import.meta.glob( + ['/*.ts', '../fixture-b/*.ts'], + { as: 'url' } +) + +export const cleverCwd1 = import.meta.glob( + './node_modules/framework/**/*.page.js' +) + +export const cleverCwd2 = import.meta.glob([ + './modules/*.ts', + '../fixture-b/*.ts', + '!**/index.ts' +]) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/a.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/a.ts new file mode 100644 index 00000000000000..facd48a0875e65 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/a.ts @@ -0,0 +1 @@ +export const name = 'a' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/b.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/b.ts new file mode 100644 index 00000000000000..0b1eb38d9087a2 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/b.ts @@ -0,0 +1 @@ +export const name = 'b' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/index.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/index.ts new file mode 100644 index 00000000000000..25b59ae7d30714 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/modules/index.ts @@ -0,0 +1,6 @@ +export { name as a } from './a' +export { name as b } from './b' + +export const name = 'index' + +export default 'indexDefault' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/node_modules/framework/pages/hello.page.js b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/node_modules/framework/pages/hello.page.js new file mode 100644 index 00000000000000..cbe518a8e79477 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/node_modules/framework/pages/hello.page.js @@ -0,0 +1,4 @@ +// A fake Page file. (This technique of globbing into `node_modules/` +// is used by vite-plugin-ssr frameworks and Hydrogen.) + +export const a = 1 diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/sibling.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/sibling.ts new file mode 100644 index 00000000000000..b286816bf5d63a --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/sibling.ts @@ -0,0 +1 @@ +export const name = 'I am your sibling!' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/a.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/a.ts new file mode 100644 index 00000000000000..facd48a0875e65 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/a.ts @@ -0,0 +1 @@ +export const name = 'a' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/b.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/b.ts new file mode 100644 index 00000000000000..0b1eb38d9087a2 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/b.ts @@ -0,0 +1 @@ +export const name = 'b' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/index.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/index.ts new file mode 100644 index 00000000000000..39bdbfd1a8befb --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-b/index.ts @@ -0,0 +1,2 @@ +export { name as a } from './a' +export { name as b } from './b' diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts new file mode 100644 index 00000000000000..985263d91db85a --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts @@ -0,0 +1,59 @@ +import { resolve } from 'path' +import { promises as fs } from 'fs' +import { describe, expect, it } from 'vitest' +import { transformGlobImport } from '../../../plugins/importMetaGlob' +import { transformWithEsbuild } from '../../../plugins/esbuild' + +describe('fixture', async () => { + const resolveId = (id: string) => id + const root = resolve(__dirname, '..') + + it('transform', async () => { + const id = resolve(__dirname, './fixture-a/index.ts') + const code = ( + await transformWithEsbuild(await fs.readFile(id, 'utf-8'), id) + ).code + + expect( + (await transformGlobImport(code, id, root, resolveId))?.s.toString() + ).toMatchSnapshot() + }) + + it('virtual modules', async () => { + const root = resolve(__dirname, './fixture-a') + const code = [ + "import.meta.glob('/modules/*.ts')", + "import.meta.glob(['/../fixture-b/*.ts'])" + ].join('\n') + expect( + ( + await transformGlobImport(code, 'virtual:module', root, resolveId) + )?.s.toString() + ).toMatchSnapshot() + + try { + await transformGlobImport( + "import.meta.glob('./modules/*.ts')", + 'virtual:module', + root, + resolveId + ) + expect('no error').toBe('should throw an error') + } catch (err) { + expect(err).toMatchInlineSnapshot( + "[Error: In virtual modules, all globs must start with '/']" + ) + } + }) + + it('transform with restoreQueryExtension', async () => { + const id = resolve(__dirname, './fixture-a/index.ts') + const code = ( + await transformWithEsbuild(await fs.readFile(id, 'utf-8'), id) + ).code + + expect( + (await transformGlobImport(code, id, root, resolveId, true))?.s.toString() + ).toMatchSnapshot() + }) +}) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts new file mode 100644 index 00000000000000..df1e0d758e8849 --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest' +import { parseImportGlob } from '../../../plugins/importMetaGlob' + +async function run(input: string) { + const items = await parseImportGlob( + input, + process.cwd(), + process.cwd(), + (id) => id + ) + return items.map((i) => ({ globs: i.globs, options: i.options })) +} + +async function runError(input: string) { + try { + await run(input) + } catch (e) { + return e + } +} + +describe('parse positives', async () => { + it('basic', async () => { + expect( + await run(` + import.meta.importGlob(\'./modules/*.ts\') + `) + ).toMatchInlineSnapshot('[]') + }) + + it('array', async () => { + expect( + await run(` + import.meta.importGlob([\'./modules/*.ts\', './dir/*.{js,ts}\']) + `) + ).toMatchInlineSnapshot('[]') + }) + + it('options with multilines', async () => { + expect( + await run(` + import.meta.importGlob([ + \'./modules/*.ts\', + "!./dir/*.{js,ts}" + ], { + eager: true, + import: 'named' + }) + `) + ).toMatchInlineSnapshot('[]') + }) + + it('options with multilines', async () => { + expect( + await run(` + const modules = import.meta.glob( + '/dir/**' + // for test: annotation contain ")" + /* + * for test: annotation contain ")" + * */ + ) + `) + ).toMatchInlineSnapshot(` + [ + { + "globs": [ + "/dir/**", + ], + "options": {}, + }, + ] + `) + }) + + it('options query', async () => { + expect( + await run(` + const modules = import.meta.glob( + '/dir/**', + { + query: { + foo: 'bar', + raw: true, + } + } + ) + `) + ).toMatchInlineSnapshot(` + [ + { + "globs": [ + "/dir/**", + ], + "options": { + "query": { + "foo": "bar", + "raw": true, + }, + }, + }, + ] + `) + }) +}) + +describe('parse negatives', async () => { + it('syntax error', async () => { + expect(await runError('import.meta.importGlob(')).toMatchInlineSnapshot( + 'undefined' + ) + }) + + it('empty', async () => { + expect(await runError('import.meta.importGlob()')).toMatchInlineSnapshot( + 'undefined' + ) + }) + + it('3 args', async () => { + expect( + await runError('import.meta.importGlob("", {}, {})') + ).toMatchInlineSnapshot('undefined') + }) + + it('in string', async () => { + expect(await runError('"import.meta.importGlob()"')).toBeUndefined() + }) + + it('variable', async () => { + expect(await runError('import.meta.importGlob(hey)')).toMatchInlineSnapshot( + 'undefined' + ) + }) + + it('template', async () => { + // eslint-disable-next-line no-template-curly-in-string + expect( + await runError('import.meta.importGlob(`hi ${hey}`)') + ).toMatchInlineSnapshot('undefined') + }) + + it('be string', async () => { + expect(await runError('import.meta.importGlob(1)')).toMatchInlineSnapshot( + 'undefined' + ) + }) + + it('be array variable', async () => { + expect( + await runError('import.meta.importGlob([hey])') + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob(["1", hey])') + ).toMatchInlineSnapshot('undefined') + }) + + it('options', async () => { + expect( + await runError('import.meta.importGlob("hey", hey)') + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob("hey", [])') + ).toMatchInlineSnapshot('undefined') + }) + + it('options props', async () => { + expect( + await runError('import.meta.importGlob("hey", { hey: 1 })') + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob("hey", { import: hey })') + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob("hey", { eager: 123 })') + ).toMatchInlineSnapshot('undefined') + }) + + it('options query', async () => { + expect( + await runError( + 'import.meta.importGlob("./*.js", { as: "raw", query: "hi" })' + ) + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob("./*.js", { query: 123 })') + ).toMatchInlineSnapshot('undefined') + expect( + await runError('import.meta.importGlob("./*.js", { query: { foo: {} } })') + ).toMatchInlineSnapshot('undefined') + expect( + await runError( + 'import.meta.importGlob("./*.js", { query: { foo: hey } })' + ) + ).toMatchInlineSnapshot('undefined') + expect( + await runError( + 'import.meta.importGlob("./*.js", { query: { foo: 123, ...a } })' + ) + ).toMatchInlineSnapshot('undefined') + }) +}) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts new file mode 100644 index 00000000000000..302df97ec92ede --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { getCommonBase } from '../../../plugins/importMetaGlob' + +describe('getCommonBase()', async () => { + it('basic', () => { + expect(getCommonBase(['/a/b/*.js', '/a/c/*.js'])).toBe('/a') + }) + it('common base', () => { + expect(getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx'])).toBe('/a/b') + }) + it('static file', () => { + expect( + getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx', '/a/b/foo.js']) + ).toBe('/a/b') + expect(getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx', '/a/foo.js'])).toBe( + '/a' + ) + }) + it('correct `scan()`', () => { + expect(getCommonBase(['/a/*.vue'])).toBe('/a') + expect(getCommonBase(['/a/some.vue'])).toBe('/a') + expect(getCommonBase(['/a/b/**/c/foo.vue', '/a/b/c/**/*.jsx'])).toBe('/a/b') + }) + it('single', () => { + expect(getCommonBase(['/a/b/c/*.vue'])).toBe('/a/b/c') + expect(getCommonBase(['/a/b/c/foo.vue'])).toBe('/a/b/c') + }) + it('no common base', () => { + expect(getCommonBase(['/a/b/*.js', '/c/a/b/*.js'])).toBe('/') + }) +}) diff --git a/packages/vite/src/node/__tests__/scan.spec.ts b/packages/vite/src/node/__tests__/scan.spec.ts index db11bcc45b284c..0f9475562365d5 100644 --- a/packages/vite/src/node/__tests__/scan.spec.ts +++ b/packages/vite/src/node/__tests__/scan.spec.ts @@ -1,4 +1,5 @@ -import { scriptRE, commentRE, importsRE } from '../optimizer/scan' +import { describe, expect, test } from 'vitest' +import { commentRE, importsRE, scriptRE } from '../optimizer/scan' import { multilineCommentsRE, singlelineCommentsRE } from '../utils' describe('optimizer-scan:script-test', () => { diff --git a/packages/vite/src/node/__tests__/utils.spec.ts b/packages/vite/src/node/__tests__/utils.spec.ts index 1162105c3f19c7..56b5db32c2caf4 100644 --- a/packages/vite/src/node/__tests__/utils.spec.ts +++ b/packages/vite/src/node/__tests__/utils.spec.ts @@ -1,3 +1,4 @@ +import { describe, expect, test } from 'vitest' import { getPotentialTsSrcPaths, injectQuery, diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index ff03352a20d7a7..73db49c1c2b7ae 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -1,52 +1,47 @@ import fs from 'fs' import path from 'path' import colors from 'picocolors' -import type { InlineConfig, ResolvedConfig } from './config' -import { resolveConfig } from './config' import type { + ExternalOption, + ModuleFormat, + OutputOptions, Plugin, RollupBuild, + RollupError, RollupOptions, - RollupWarning, - WarningHandler, - OutputOptions, RollupOutput, - ExternalOption, - WatcherOptions, + RollupWarning, RollupWatcher, - RollupError, - ModuleFormat + WarningHandler, + WatcherOptions } from 'rollup' import type Rollup from 'rollup' +import type { Terser } from 'types/terser' +import commonjsPlugin from '@rollup/plugin-commonjs' +import type { RollupCommonJSOptions } from 'types/commonjs' +import type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars' +import type { TransformOptions } from 'esbuild' +import type { InlineConfig, ResolvedConfig } from './config' +import { resolveConfig } from './config' import { buildReporterPlugin } from './plugins/reporter' import { buildEsbuildPlugin } from './plugins/esbuild' import { terserPlugin } from './plugins/terser' -import type { Terser } from 'types/terser' import { copyDir, emptyDir, lookupFile, normalizePath } from './utils' import { manifestPlugin } from './plugins/manifest' -import commonjsPlugin from '@rollup/plugin-commonjs' -import type { RollupCommonJSOptions } from 'types/commonjs' -import dynamicImportVars from '@rollup/plugin-dynamic-import-vars' -import type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars' import type { Logger } from './logger' -import type { TransformOptions } from 'esbuild' import { dataURIPlugin } from './plugins/dataUri' import { buildImportAnalysisPlugin } from './plugins/importAnalysisBuild' import { resolveSSRExternal, shouldExternalizeForSSR } from './ssr/ssrExternal' import { ssrManifestPlugin } from './ssr/ssrManifestPlugin' import type { DepOptimizationMetadata } from './optimizer' -import { getDepsCacheDir, findKnownImports } from './optimizer' +import { findKnownImports, getDepsCacheDir } from './optimizer' import { assetImportMetaUrlPlugin } from './plugins/assetImportMetaUrl' import { loadFallbackPlugin } from './plugins/loadFallback' +import type { PackageData } from './packages' import { watchPackageDataPlugin } from './packages' import { ensureWatchPlugin } from './plugins/ensureWatch' export interface BuildOptions { - /** - * Base public path when served in production. - * @deprecated `base` is now a root-level config option. - */ - base?: string /** * Compatibility transform target. The transform is performed with esbuild * and the lowest supported target is es2015/es6. Note this only handles @@ -70,13 +65,6 @@ export interface BuildOptions { * @default true */ polyfillModulePreload?: boolean - /** - * whether to inject dynamic import polyfill. - * Note: does not apply to library mode. - * @default false - * @deprecated use plugin-legacy for browsers that don't support dynamic import - */ - polyfillDynamicImport?: boolean /** * Directory relative from `root` where build output will be placed. If the * directory exists, it will be removed before the build. @@ -130,10 +118,6 @@ export interface BuildOptions { * https://terser.org/docs/api-reference#minify-options */ terserOptions?: Terser.MinifyOptions - /** - * @deprecated Vite now uses esbuild for CSS minification. - */ - cleanCssOptions?: any /** * Will be merged with internal rollup options. * https://rollupjs.org/guide/en/#big-list-of-options @@ -198,12 +182,6 @@ export interface BuildOptions { * Can slightly improve build speed. */ reportCompressedSize?: boolean - /** - * Set to false to disable brotli compressed size reporting for build. - * Can slightly improve build speed. - * @deprecated use `build.reportCompressedSize` instead. - */ - brotliSize?: boolean /** * Adjust chunk size warning limit (in kbs). * @default 500 @@ -225,13 +203,7 @@ export interface LibraryOptions { export type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' -export type ResolvedBuildOptions = Required< - Omit< - BuildOptions, - // make deprecated options optional - 'base' | 'cleanCssOptions' | 'polyfillDynamicImport' | 'brotliSize' - > -> +export type ResolvedBuildOptions = Required export function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions { const resolved: ResolvedBuildOptions = { @@ -253,7 +225,6 @@ export function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions { ssr: false, ssrManifest: false, reportCompressedSize: true, - // brotliSize: true, chunkSizeWarningLimit: 500, watch: null, ...raw, @@ -313,7 +284,6 @@ export function resolveBuildPlugins(config: ResolvedConfig): { watchPackageDataPlugin(config), commonjsPlugin(options.commonjsOptions), dataURIPlugin(), - dynamicImportVars(options.dynamicImportVarsOptions), assetImportMetaUrlPlugin(config), ...(options.rollupOptions.plugins ? (options.rollupOptions.plugins.filter(Boolean) as Plugin[]) @@ -451,15 +421,6 @@ async function doBuild( try { const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => { - // @ts-ignore - if (output.output) { - config.logger.warn( - `You've set "rollupOptions.output.output" in your config. ` + - `This is deprecated and will override all Vite.js default output options. ` + - `Please use "rollupOptions.output" instead.` - ) - } - return { dir: outDir, format: ssr ? 'cjs' : 'es', @@ -538,9 +499,6 @@ async function doBuild( } }) - // stop watching - watcher.close() - return watcher } @@ -601,9 +559,11 @@ function prepareOutDir( } } -function getPkgName(root: string) { - const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`) +function getPkgJson(root: string): PackageData['data'] { + return JSON.parse(lookupFile(root, ['package.json']) || `{}`) +} +function getPkgName(name: string) { return name?.startsWith('@') ? name.split('/')[1] : name } @@ -616,14 +576,23 @@ export function resolveLibFilename( return libOptions.fileName(format) } - const name = libOptions.fileName || getPkgName(root) + const packageJson = getPkgJson(root) + const name = libOptions.fileName || getPkgName(packageJson.name) if (!name) throw new Error( 'Name in package.json is required if option "build.lib.fileName" is not provided.' ) - return `${name}.${format}.js` + let extension: string + + if (packageJson?.type === 'module') { + extension = format === 'cjs' || format === 'umd' ? 'cjs' : 'js' + } else { + extension = format === 'es' ? 'mjs' : 'js' + } + + return `${name}.${format}.${extension}` } function resolveBuildOutputs( diff --git a/packages/vite/src/node/cleanString.ts b/packages/vite/src/node/cleanString.ts deleted file mode 100644 index 3d623dce79c0d3..00000000000000 --- a/packages/vite/src/node/cleanString.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { RollupError } from 'rollup' -// bank on the non-overlapping nature of regex matches and combine all filters into one giant regex -// /`([^`\$\{\}]|\$\{(`|\g<1>)*\})*`/g can match nested string template -// but js not support match expression(\g<0>). so clean string template(`...`) in other ways. -const stringsRE = /"([^"\r\n]|(?<=\\)")*"|'([^'\r\n]|(?<=\\)')*'/.source -const commentsRE = /\/\*(.|[\r\n])*?\*\/|\/\/.*/.source -const cleanerRE = new RegExp(`${stringsRE}|${commentsRE}`, 'g') - -const blankReplacer = (s: string) => ' '.repeat(s.length) -const stringBlankReplacer = (s: string) => - `${s[0]}${'\0'.repeat(s.length - 2)}${s[0]}` - -export function emptyString(raw: string): string { - let res = raw.replace(cleanerRE, (s: string) => - s[0] === '/' ? blankReplacer(s) : stringBlankReplacer(s) - ) - - let lastEnd = 0 - let start = 0 - while ((start = res.indexOf('`', lastEnd)) >= 0) { - let clean - ;[clean, lastEnd] = lexStringTemplateExpression(res, start) - res = replaceAt(res, start, lastEnd, clean) - } - - return res -} - -const enum LexerState { - // template string - inTemplateString, - inInterpolationExpression, - inObjectExpression, - // strings - inSingleQuoteString, - inDoubleQuoteString, - // comments - inMultilineCommentsRE, - inSinglelineCommentsRE -} - -function replaceAt( - string: string, - start: number, - end: number, - replacement: string -): string { - return string.slice(0, start) + replacement + string.slice(end) -} - -/** - * lex string template and clean it. - */ -function lexStringTemplateExpression( - code: string, - start: number -): [string, number] { - let state = LexerState.inTemplateString as LexerState - let clean = '`' - const opStack: LexerState[] = [state] - - function pushStack(newState: LexerState) { - state = newState - opStack.push(state) - } - - function popStack() { - opStack.pop() - state = opStack[opStack.length - 1] - } - - let i = start + 1 - outer: for (; i < code.length; i++) { - const char = code.charAt(i) - switch (state) { - case LexerState.inTemplateString: - if (char === '$' && code.charAt(i + 1) === '{') { - pushStack(LexerState.inInterpolationExpression) - clean += '${' - i++ // jump next - } else if (char === '`') { - popStack() - clean += char - if (opStack.length === 0) { - break outer - } - } else { - clean += '\0' - } - break - case LexerState.inInterpolationExpression: - if (char === '{') { - pushStack(LexerState.inObjectExpression) - clean += char - } else if (char === '}') { - popStack() - clean += char - } else if (char === '`') { - pushStack(LexerState.inTemplateString) - clean += char - } else { - clean += char - } - break - case LexerState.inObjectExpression: - if (char === '}') { - popStack() - clean += char - } else if (char === '`') { - pushStack(LexerState.inTemplateString) - clean += char - } else { - clean += char - } - break - default: - throw new Error('unknown string template lexer state') - } - } - - if (opStack.length !== 0) { - error(start) - } - - return [clean, i + 1] -} - -function error(pos: number) { - const err = new Error( - `can not match string template expression.` - ) as RollupError - err.pos = pos - throw err -} diff --git a/packages/vite/src/node/cli.ts b/packages/vite/src/node/cli.ts index 89412a825e9fc1..9ee807f505e016 100644 --- a/packages/vite/src/node/cli.ts +++ b/packages/vite/src/node/cli.ts @@ -1,6 +1,6 @@ +import { performance } from 'perf_hooks' import { cac } from 'cac' import colors from 'picocolors' -import { performance } from 'perf_hooks' import type { BuildOptions } from './build' import type { ServerOptions } from './server' import type { LogLevel } from './logger' diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index d242ac632c220e..138514579f3ee0 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -1,45 +1,45 @@ import fs from 'fs' import path from 'path' +import { parse as parseUrl, pathToFileURL } from 'url' +import { performance } from 'perf_hooks' +import colors from 'picocolors' +import dotenv from 'dotenv' +import dotenvExpand from 'dotenv-expand' +import type { Alias, AliasOptions } from 'types/alias' +import { createFilter } from '@rollup/pluginutils' +import aliasPlugin from '@rollup/plugin-alias' +import { build } from 'esbuild' +import type { RollupOptions } from 'rollup' import type { Plugin } from './plugin' import type { BuildOptions } from './build' import { resolveBuildOptions } from './build' import type { ResolvedServerOptions, ServerOptions } from './server' import { resolveServerOptions } from './server' -import type { ResolvedPreviewOptions, PreviewOptions } from './preview' +import type { PreviewOptions, ResolvedPreviewOptions } from './preview' import { resolvePreviewOptions } from './preview' import type { CSSOptions } from './plugins/css' import { arraify, createDebugger, + dynamicImport, isExternalUrl, isObject, lookupFile, - normalizePath, - dynamicImport + normalizePath } from './utils' import { resolvePlugins } from './plugins' -import colors from 'picocolors' import type { ESBuildOptions } from './plugins/esbuild' -import dotenv from 'dotenv' -import dotenvExpand from 'dotenv-expand' -import type { Alias, AliasOptions } from 'types/alias' -import { CLIENT_ENTRY, ENV_ENTRY, DEFAULT_ASSETS_RE } from './constants' +import { CLIENT_ENTRY, DEFAULT_ASSETS_RE, ENV_ENTRY } from './constants' import type { InternalResolveOptions, ResolveOptions } from './plugins/resolve' import { resolvePlugin } from './plugins/resolve' -import type { Logger, LogLevel } from './logger' +import type { LogLevel, Logger } from './logger' import { createLogger } from './logger' import type { DepOptimizationOptions } from './optimizer' -import { createFilter } from '@rollup/pluginutils' -import type { ResolvedBuildOptions } from '.' -import { parse as parseUrl, pathToFileURL } from 'url' import type { JsonOptions } from './plugins/json' import type { PluginContainer } from './server/pluginContainer' import { createPluginContainer } from './server/pluginContainer' -import aliasPlugin from '@rollup/plugin-alias' -import { build } from 'esbuild' -import { performance } from 'perf_hooks' import type { PackageCache } from './packages' -import type { RollupOptions } from 'rollup' +import type { ResolvedBuildOptions } from '.' const debug = createDebugger('vite:config') @@ -152,6 +152,14 @@ export interface UserConfig { * @alpha */ ssr?: SSROptions + /** + * Experimental features + * + * Features under this field are addressed to be changed that might NOT follow semver. + * Please be careful and always pin Vite's version when using them. + * @experimental + */ + experimental?: ExperimentalOptions /** * Log level. * Default: 'info' @@ -176,17 +184,6 @@ export interface UserConfig { * @default 'VITE_' */ envPrefix?: string | string[] - /** - * Import aliases - * @deprecated use `resolve.alias` instead - */ - alias?: AliasOptions - /** - * Force Vite to always resolve listed dependencies to the same copy (from - * project root). - * @deprecated use `resolve.dedupe` instead - */ - dedupe?: string[] /** * Worker bundle options */ @@ -210,6 +207,16 @@ export interface UserConfig { } } +export interface ExperimentalOptions { + /** + * Append fake `&lang.(ext)` when queries are specified, to preseve the file extension for following plugins to process. + * + * @experimental + * @default false + */ + importGlobRestoreExtension?: boolean +} + export type SSRTarget = 'node' | 'webworker' export interface SSROptions { @@ -235,10 +242,7 @@ export interface InlineConfig extends UserConfig { } export type ResolvedConfig = Readonly< - Omit< - UserConfig, - 'plugins' | 'alias' | 'dedupe' | 'assetsInclude' | 'optimizeDeps' | 'worker' - > & { + Omit & { configFile: string | undefined configFileDependencies: string[] inlineConfig: InlineConfig @@ -261,7 +265,7 @@ export type ResolvedConfig = Readonly< assetsInclude: (file: string) => boolean logger: Logger createResolver: (options?: Partial) => ResolveFn - optimizeDeps: Omit + optimizeDeps: DepOptimizationOptions /** @internal */ packageCache: PackageCache worker: ResolveWorkerOptions @@ -370,12 +374,11 @@ export async function resolveConfig( // @ts-ignore because @rollup/plugin-alias' type doesn't allow function // replacement, but its implementation does work with function values. clientAlias, - config.resolve?.alias || config.alias || [] + config.resolve?.alias || [] ) ) const resolveOptions: ResolvedConfig['resolve'] = { - dedupe: config.dedupe, ...config.resolve, alias: resolvedAlias } @@ -461,7 +464,7 @@ export async function resolveConfig( ) : '' - const server = resolveServerOptions(resolvedRoot, config.server) + const server = resolveServerOptions(resolvedRoot, config.server, logger) const optimizeDeps = config.optimizeDeps || {} @@ -501,7 +504,6 @@ export async function resolveConfig( optimizeDeps: { ...optimizeDeps, esbuildOptions: { - keepNames: optimizeDeps.keepNames, preserveSymlinks: config.resolve?.preserveSymlinks, ...optimizeDeps.esbuildOptions } @@ -540,117 +542,6 @@ export async function resolveConfig( }) } - // TODO Deprecation warnings - remove when out of beta - - const logDeprecationWarning = ( - deprecatedOption: string, - hint: string, - error?: Error - ) => { - logger.warn( - colors.yellow( - colors.bold( - `(!) "${deprecatedOption}" option is deprecated. ${hint}${ - error ? `\n${error.stack}` : '' - }` - ) - ) - ) - } - - if (config.build?.base) { - logDeprecationWarning( - 'build.base', - '"base" is now a root-level config option.' - ) - config.base = config.build.base - } - Object.defineProperty(resolvedBuildOptions, 'base', { - enumerable: false, - get() { - logDeprecationWarning( - 'build.base', - '"base" is now a root-level config option.', - new Error() - ) - return resolved.base - } - }) - - if (config.alias) { - logDeprecationWarning('alias', 'Use "resolve.alias" instead.') - } - Object.defineProperty(resolved, 'alias', { - enumerable: false, - get() { - logDeprecationWarning( - 'alias', - 'Use "resolve.alias" instead.', - new Error() - ) - return resolved.resolve.alias - } - }) - - if (config.dedupe) { - logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.') - } - Object.defineProperty(resolved, 'dedupe', { - enumerable: false, - get() { - logDeprecationWarning( - 'dedupe', - 'Use "resolve.dedupe" instead.', - new Error() - ) - return resolved.resolve.dedupe - } - }) - - if (optimizeDeps.keepNames) { - logDeprecationWarning( - 'optimizeDeps.keepNames', - 'Use "optimizeDeps.esbuildOptions.keepNames" instead.' - ) - } - Object.defineProperty(resolved.optimizeDeps, 'keepNames', { - enumerable: false, - get() { - logDeprecationWarning( - 'optimizeDeps.keepNames', - 'Use "optimizeDeps.esbuildOptions.keepNames" instead.', - new Error() - ) - return resolved.optimizeDeps.esbuildOptions?.keepNames - } - }) - - if (config.build?.polyfillDynamicImport) { - logDeprecationWarning( - 'build.polyfillDynamicImport', - '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.' - ) - } - - Object.defineProperty(resolvedBuildOptions, 'polyfillDynamicImport', { - enumerable: false, - get() { - logDeprecationWarning( - 'build.polyfillDynamicImport', - '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.', - new Error() - ) - return false - } - }) - - if (config.build?.cleanCssOptions) { - logDeprecationWarning( - 'build.cleanCssOptions', - 'Vite now uses esbuild for CSS minification.' - ) - } - if (config.build?.terserOptions && config.build.minify !== 'terser') { logger.warn( colors.yellow( @@ -745,7 +636,11 @@ function mergeConfigRecursively( } else if (key === 'assetsInclude' && rootPath === '') { merged[key] = [].concat(existing, value) continue - } else if (key === 'noExternal' && (existing === true || value === true)) { + } else if ( + key === 'noExternal' && + rootPath === 'ssr' && + (existing === true || value === true) + ) { merged[key] = true continue } diff --git a/packages/vite/src/node/http.ts b/packages/vite/src/node/http.ts index bfc2ddbe32a302..1aa924282483b8 100644 --- a/packages/vite/src/node/http.ts +++ b/packages/vite/src/node/http.ts @@ -1,13 +1,13 @@ import fs, { promises as fsp } from 'fs' import path from 'path' import type { - OutgoingHttpHeaders as HttpServerHeaders, - Server as HttpServer + Server as HttpServer, + OutgoingHttpHeaders as HttpServerHeaders } from 'http' import type { ServerOptions as HttpsServerOptions } from 'https' +import type { Connect } from 'types/connect' import { isObject } from './utils' import type { ProxyOptions } from './server/middlewares/proxy' -import type { Connect } from 'types/connect' import type { Logger } from './logger' export interface CommonServerOptions { @@ -104,6 +104,9 @@ export async function resolveHttpServer( } else { return require('http2').createSecureServer( { + // Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM + // errors on large numbers of requests + maxSessionMemory: 1000, ...httpsOptions, allowHTTP1: true }, diff --git a/packages/vite/src/node/importGlob.ts b/packages/vite/src/node/importGlob.ts deleted file mode 100644 index a759bee2b5fa59..00000000000000 --- a/packages/vite/src/node/importGlob.ts +++ /dev/null @@ -1,263 +0,0 @@ -import path from 'path' -import { promises as fsp } from 'fs' -import glob from 'fast-glob' -import JSON5 from 'json5' -import { - isModernFlag, - preloadMethod, - preloadMarker -} from './plugins/importAnalysisBuild' -import { isCSSRequest } from './plugins/css' -import { - cleanUrl, - singlelineCommentsRE, - multilineCommentsRE, - blankReplacer, - normalizePath -} from './utils' -import type { RollupError } from 'rollup' -import type { Logger } from '.' -import colors from 'picocolors' - -interface GlobParams { - base: string - pattern: string - parentDepth: number - isAbsolute: boolean -} - -interface GlobOptions { - as?: string - /** - * @deprecated - */ - assert?: { - type: string - } -} - -function formatGlobRelativePattern(base: string, pattern: string): GlobParams { - let parentDepth = 0 - while (pattern.startsWith('../')) { - pattern = pattern.slice(3) - base = path.resolve(base, '../') - parentDepth++ - } - if (pattern.startsWith('./')) { - pattern = pattern.slice(2) - } - - return { base, pattern, parentDepth, isAbsolute: false } -} - -export async function transformImportGlob( - source: string, - pos: number, - importer: string, - importIndex: number, - root: string, - logger: Logger, - normalizeUrl?: (url: string, pos: number) => Promise<[string, string]>, - resolve?: (url: string, importer?: string) => Promise, - preload = true -): Promise<{ - importsString: string - imports: string[] - exp: string - endIndex: number - isEager: boolean - pattern: string - base: string -}> { - const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager' - const isEagerDefault = - isEager && source.slice(pos + 21, pos + 28) === 'Default' - - const err = (msg: string) => { - const e = new Error(`Invalid glob import syntax: ${msg}`) - ;(e as any).pos = pos - return e - } - - importer = cleanUrl(importer) - const importerBasename = path.basename(importer) - - const [userPattern, options, endIndex] = lexGlobPattern(source, pos) - - let globParams: GlobParams | null = null - if (userPattern.startsWith('/')) { - globParams = { - isAbsolute: true, - base: path.resolve(root), - pattern: userPattern.slice(1), - parentDepth: 0 - } - } else if (userPattern.startsWith('.')) { - globParams = formatGlobRelativePattern(path.dirname(importer), userPattern) - } else if (resolve) { - const resolvedId = await resolve(userPattern, importer) - if (resolvedId) { - const importerDirname = path.dirname(importer) - globParams = formatGlobRelativePattern( - importerDirname, - normalizePath(path.relative(importerDirname, resolvedId)) - ) - } - } - - if (!globParams) { - throw err( - `pattern must start with "." or "/" (relative to project root) or alias path` - ) - } - const { base, parentDepth, isAbsolute, pattern } = globParams - - const files = glob.sync(pattern, { - cwd: base, - // Ignore node_modules by default unless explicitly indicated in the pattern - ignore: /(^|\/)node_modules\//.test(pattern) ? [] : ['**/node_modules/**'] - }) - const imports: string[] = [] - let importsString = `` - let entries = `` - for (let i = 0; i < files.length; i++) { - // skip importer itself - if (files[i] === importerBasename) continue - const file = isAbsolute - ? `/${files[i]}` - : parentDepth - ? `${'../'.repeat(parentDepth)}${files[i]}` - : `./${files[i]}` - let importee = file - if (normalizeUrl) { - ;[importee] = await normalizeUrl(file, pos) - } - imports.push(importee) - // TODO remove assert syntax for the Vite 3.0 release. - const isRawAssert = options?.assert?.type === 'raw' - const isRawType = options?.as === 'raw' - if (isRawType || isRawAssert) { - if (isRawAssert) { - logger.warn( - colors.yellow( - colors.bold( - "(!) import.meta.glob('...', { assert: { type: 'raw' }}) is deprecated. Use import.meta.glob('...', { as: 'raw' }) instead." - ) - ) - ) - } - entries += ` ${JSON.stringify(file)}: ${JSON.stringify( - await fsp.readFile(path.join(base, files[i]), 'utf-8') - )},` - } else { - const importeeUrl = isCSSRequest(importee) ? `${importee}?used` : importee - if (isEager) { - const identifier = `__glob_${importIndex}_${i}` - // css imports injecting a ?used query to export the css string - importsString += `import ${ - isEagerDefault ? `` : `* as ` - }${identifier} from ${JSON.stringify(importeeUrl)};` - entries += ` ${JSON.stringify(file)}: ${identifier},` - } else { - let imp = `import(${JSON.stringify(importeeUrl)})` - if (!normalizeUrl && preload) { - imp = - `(${isModernFlag}` + - `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` + - `: ${imp})` - } - entries += ` ${JSON.stringify(file)}: () => ${imp},` - } - } - } - - return { - imports, - importsString, - exp: `{${entries}}`, - endIndex, - isEager, - pattern, - base - } -} - -const enum LexerState { - inCall, - inSingleQuoteString, - inDoubleQuoteString, - inTemplateString -} - -function lexGlobPattern( - code: string, - pos: number -): [string, GlobOptions, number] { - let state = LexerState.inCall - let pattern = '' - - let i = code.indexOf(`(`, pos) + 1 - outer: for (; i < code.length; i++) { - const char = code.charAt(i) - switch (state) { - case LexerState.inCall: - if (char === `'`) { - state = LexerState.inSingleQuoteString - } else if (char === `"`) { - state = LexerState.inDoubleQuoteString - } else if (char === '`') { - state = LexerState.inTemplateString - } else if (/\s/.test(char)) { - continue - } else { - error(i) - } - break - case LexerState.inSingleQuoteString: - if (char === `'`) { - break outer - } else { - pattern += char - } - break - case LexerState.inDoubleQuoteString: - if (char === `"`) { - break outer - } else { - pattern += char - } - break - case LexerState.inTemplateString: - if (char === '`') { - break outer - } else { - pattern += char - } - break - default: - throw new Error('unknown import.meta.glob lexer state') - } - } - const noCommentCode = code - .slice(i + 1) - .replace(singlelineCommentsRE, blankReplacer) - .replace(multilineCommentsRE, blankReplacer) - - const endIndex = noCommentCode.indexOf(')') - const optionString = noCommentCode.substring(0, endIndex) - const commaIndex = optionString.indexOf(',') - - let options = {} - if (commaIndex > -1) { - options = JSON5.parse(optionString.substring(commaIndex + 1)) - } - return [pattern, options, endIndex + i + 2] -} - -function error(pos: number) { - const err = new Error( - `import.meta.glob() can only accept string literals.` - ) as RollupError - err.pos = pos - throw err -} diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts index 2e849d846527ca..0d401363b8a3b6 100644 --- a/packages/vite/src/node/index.ts +++ b/packages/vite/src/node/index.ts @@ -4,7 +4,7 @@ export { preview } from './preview' export { build } from './build' export { optimizeDeps } from './optimizer' export { send } from './server/send' -export { createLogger, printHttpServerUrls } from './logger' +export { createLogger } from './logger' export { formatPostcssSourceMap } from './plugins/css' export { transformWithEsbuild } from './plugins/esbuild' export { resolvePackageEntry } from './plugins/resolve' @@ -33,6 +33,7 @@ export type { export type { PreviewOptions, PreviewServer, + PreviewServerHook, ResolvedPreviewOptions } from './preview' export type { @@ -73,6 +74,9 @@ export type { TransformOptions as EsbuildTransformOptions } from 'esbuild' export type { ESBuildOptions, ESBuildTransformResult } from './plugins/esbuild' export type { Manifest, ManifestChunk } from './plugins/manifest' export type { ResolveOptions, InternalResolveOptions } from './plugins/resolve' +export type { SplitVendorChunkCache } from './plugins/splitVendorChunk' +import type { ChunkMetadata } from './plugins/metadata' + export type { WebSocketServer, WebSocketClient, @@ -87,6 +91,7 @@ export type { TransformResult } from './server/transformRequest' export type { HmrOptions, HmrContext } from './server/hmr' + export type { HMRPayload, ConnectedPayload, @@ -110,9 +115,12 @@ export type { RollupCommonJSOptions } from 'types/commonjs' export type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars' export type { CustomEventMap, InferCustomEventPayload } from 'types/customEvent' export type { Matcher, AnymatchPattern, AnymatchFn } from 'types/anymatch' -export type { SplitVendorChunkCache } from './plugins/splitVendorChunk' - -import type { ChunkMetadata } from './plugins/metadata' +export type { + ImportGlobFunction, + ImportGlobEagerFunction, + ImportGlobOptions, + KnownAsTypeMap +} from 'types/importGlob' declare module 'rollup' { export interface RenderedChunk { diff --git a/packages/vite/src/node/logger.ts b/packages/vite/src/node/logger.ts index 8ece2dd8746b7f..c0f316ffed2698 100644 --- a/packages/vite/src/node/logger.ts +++ b/packages/vite/src/node/logger.ts @@ -1,14 +1,14 @@ /* eslint no-console: 0 */ -import colors from 'picocolors' import type { AddressInfo, Server } from 'net' import os from 'os' import readline from 'readline' +import colors from 'picocolors' import type { RollupError } from 'rollup' -import type { ResolvedConfig } from '.' import type { CommonServerOptions } from './http' import type { Hostname } from './utils' import { resolveHostname } from './utils' +import type { ResolvedConfig } from '.' export type LogType = 'error' | 'warn' | 'info' export type LogLevel = LogType | 'silent' @@ -144,16 +144,6 @@ export function createLogger( return logger } -/** - * @deprecated Use `server.printUrls()` instead - */ -export function printHttpServerUrls( - server: Server, - config: ResolvedConfig -): void { - printCommonServerUrls(server, config.server, config) -} - export function printCommonServerUrls( server: Server, options: CommonServerOptions, diff --git a/packages/vite/src/node/optimizer/esbuildDepPlugin.ts b/packages/vite/src/node/optimizer/esbuildDepPlugin.ts index 4303be0ec876e7..9fcc649ef394e3 100644 --- a/packages/vite/src/node/optimizer/esbuildDepPlugin.ts +++ b/packages/vite/src/node/optimizer/esbuildDepPlugin.ts @@ -1,13 +1,13 @@ import path from 'path' -import type { Plugin, ImportKind } from 'esbuild' +import type { ImportKind, Plugin } from 'esbuild' import { KNOWN_ASSET_TYPES } from '../constants' import type { ResolvedConfig } from '..' import { - isRunningWithYarnPnp, flattenId, - normalizePath, isExternalUrl, - moduleListContains + isRunningWithYarnPnp, + moduleListContains, + normalizePath } from '../utils' import { browserExternalId } from '../plugins/resolve' import type { ExportsData } from '.' diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 3828cb2fbce18b..53bffb13e604d0 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -1,25 +1,27 @@ import fs from 'fs' import path from 'path' +import { createHash } from 'crypto' +import { performance } from 'perf_hooks' import _debug from 'debug' import colors from 'picocolors' -import { createHash } from 'crypto' import type { BuildOptions as EsbuildBuildOptions } from 'esbuild' import { build } from 'esbuild' +import { init, parse } from 'es-module-lexer' import type { ResolvedConfig } from '../config' import { createDebugger, emptyDir, + flattenId, lookupFile, + normalizeId, normalizePath, - writeFile, - flattenId, - normalizeId + removeDirSync, + renameDir, + writeFile } from '../utils' +import { transformWithEsbuild } from '../plugins/esbuild' import { esbuildDepPlugin } from './esbuildDepPlugin' -import { init, parse } from 'es-module-lexer' import { scanImports } from './scan' -import { transformWithEsbuild } from '../plugins/esbuild' -import { performance } from 'perf_hooks' export const debuggerViteDeps = createDebugger('vite:deps') const debug = debuggerViteDeps @@ -70,7 +72,6 @@ export interface DepOptimizationOptions { * * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option * - `plugins` are merged with Vite's dep plugin - * - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames` * * https://esbuild.github.io/api */ @@ -87,10 +88,6 @@ export interface DepOptimizationOptions { | 'outExtension' | 'metafile' > - /** - * @deprecated use `esbuildOptions.keepNames` - */ - keepNames?: boolean /** * List of file extensions that can be optimized. A corresponding esbuild * plugin must exist to handle the specific extension. @@ -116,7 +113,7 @@ export interface DepOptimizationResult { * the page reload will be delayed until the next rerun so we need * to be able to discard the result */ - commit: () => void + commit: () => Promise cancel: () => void } @@ -194,7 +191,7 @@ export async function optimizeDeps( const result = await runOptimizeDeps(config, depsInfo) - result.commit() + await result.commit() return result.metadata } @@ -376,7 +373,7 @@ export async function runOptimizeDeps( metadata, commit() { // Write metadata file, delete `deps` folder and rename the `processing` folder to `deps` - commitProcessingDepsCacheSync() + return commitProcessingDepsCacheSync() }, cancel } @@ -445,7 +442,7 @@ export async function runOptimizeDeps( } const define: Record = { - 'process.env.NODE_ENV': JSON.stringify(config.mode) + 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode) } for (const key in config.define) { const value = config.define[key] @@ -529,16 +526,16 @@ export async function runOptimizeDeps( metadata, commit() { // Write metadata file, delete `deps` folder and rename the new `processing` folder to `deps` in sync - commitProcessingDepsCacheSync() + return commitProcessingDepsCacheSync() }, cancel } - function commitProcessingDepsCacheSync() { + async function commitProcessingDepsCacheSync() { // Processing is done, we can now replace the depsCacheDir with processingCacheDir // Rewire the file paths from the temporal processing dir to the final deps cache dir removeDirSync(depsCacheDir) - fs.renameSync(processingCacheDir, depsCacheDir) + await renameDir(processingCacheDir, depsCacheDir) } function cancel() { @@ -546,13 +543,6 @@ export async function runOptimizeDeps( } } -function removeDirSync(dir: string) { - if (fs.existsSync(dir)) { - const rmSync = fs.rmSync ?? fs.rmdirSync // TODO: Remove after support for Node 12 is dropped - rmSync(dir, { recursive: true }) - } -} - export async function findKnownImports( config: ResolvedConfig ): Promise { @@ -790,7 +780,7 @@ export function getDepHash(config: ResolvedConfig): string { // only a subset of config options that can affect dep optimization content += JSON.stringify( { - mode: config.mode, + mode: process.env.NODE_ENV || config.mode, root: config.root, define: config.define, resolve: config.resolve, diff --git a/packages/vite/src/node/optimizer/registerMissing.ts b/packages/vite/src/node/optimizer/registerMissing.ts index ee4824389c202b..1efb9e02261ae7 100644 --- a/packages/vite/src/node/optimizer/registerMissing.ts +++ b/packages/vite/src/node/optimizer/registerMissing.ts @@ -1,24 +1,24 @@ import colors from 'picocolors' import _debug from 'debug' +import type { ViteDevServer } from '..' import { - runOptimizeDeps, - getOptimizedDepPath, - getHash, - depsFromOptimizedDepInfo, - newDepOptimizationProcessing, - loadCachedDepOptimizationMetadata, - createOptimizedDepsMetadata, addOptimizedDepInfo, - discoverProjectDependencies, + createOptimizedDepsMetadata, + debuggerViteDeps as debug, + depsFromOptimizedDepInfo, depsLogString, - debuggerViteDeps as debug + discoverProjectDependencies, + getHash, + getOptimizedDepPath, + loadCachedDepOptimizationMetadata, + newDepOptimizationProcessing, + runOptimizeDeps } from '.' import type { DepOptimizationProcessing, OptimizedDepInfo, OptimizedDeps } from '.' -import type { ViteDevServer } from '..' const isDebugEnabled = _debug('vite:deps').enabled @@ -189,8 +189,8 @@ export function createOptimizedDeps(server: ViteDevServer): OptimizedDeps { ) }) - const commitProcessing = () => { - processingResult.commit() + const commitProcessing = async () => { + await processingResult.commit() // While optimizeDeps is running, new missing deps may be discovered, // in which case they will keep being added to metadata.discovered @@ -240,7 +240,7 @@ export function createOptimizedDeps(server: ViteDevServer): OptimizedDeps { } if (!needsReload) { - commitProcessing() + await commitProcessing() if (!isDebugEnabled) { if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle) @@ -270,7 +270,7 @@ export function createOptimizedDeps(server: ViteDevServer): OptimizedDeps { } ) } else { - commitProcessing() + await commitProcessing() if (!isDebugEnabled) { if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle) @@ -296,7 +296,6 @@ export function createOptimizedDeps(server: ViteDevServer): OptimizedDeps { // Reset missing deps, let the server rediscover the dependencies metadata.discovered = {} - fullReload() } currentlyProcessing = false diff --git a/packages/vite/src/node/optimizer/scan.ts b/packages/vite/src/node/optimizer/scan.ts index ef59a35b1d22d3..157c8d28db1083 100644 --- a/packages/vite/src/node/optimizer/scan.ts +++ b/packages/vite/src/node/optimizer/scan.ts @@ -1,35 +1,33 @@ import fs from 'fs' import path from 'path' +import { performance } from 'perf_hooks' import glob from 'fast-glob' -import type { ResolvedConfig, Logger } from '..' -import type { Loader, Plugin, OnLoadResult } from 'esbuild' -import { build, transform } from 'esbuild' +import type { Loader, OnLoadResult, Plugin } from 'esbuild' +import { build } from 'esbuild' +import colors from 'picocolors' +import type { ResolvedConfig } from '..' import { - KNOWN_ASSET_TYPES, JS_TYPES_RE, - SPECIAL_QUERY_RE, - OPTIMIZABLE_ENTRY_RE + KNOWN_ASSET_TYPES, + OPTIMIZABLE_ENTRY_RE, + SPECIAL_QUERY_RE } from '../constants' import { + cleanUrl, createDebugger, - normalizePath, + dataUrlRE, + externalRE, isObject, - cleanUrl, moduleListContains, - externalRE, - dataUrlRE, multilineCommentsRE, + normalizePath, singlelineCommentsRE, - virtualModuleRE, - virtualModulePrefix + virtualModulePrefix, + virtualModuleRE } from '../utils' import type { PluginContainer } from '../server/pluginContainer' import { createPluginContainer } from '../server/pluginContainer' -import { init, parse } from 'es-module-lexer' -import MagicString from 'magic-string' -import { transformImportGlob } from '../importGlob' -import { performance } from 'perf_hooks' -import colors from 'picocolors' +import { transformGlobImport } from '../plugins/importMetaGlob' const debug = createDebugger('vite:deps') @@ -77,9 +75,7 @@ export async function scanImports(config: ResolvedConfig): Promise<{ // Non-supported entry file types and virtual files should not be scanned for // dependencies. entries = entries.filter( - (entry) => - (JS_TYPES_RE.test(entry) || htmlTypesRE.test(entry)) && - fs.existsSync(entry) + (entry) => isScannable(entry) && fs.existsSync(entry) ) if (!entries.length) { @@ -300,19 +296,18 @@ function esbuildScanPlugin( (loader.startsWith('ts') ? extractImportPaths(content) : '') const key = `${path}?id=${scriptId++}` - if (contents.includes('import.meta.glob')) { scripts[key] = { - // transformGlob already transforms to js loader: 'js', - contents: await transformGlob( - contents, - path, - config.root, - loader, - resolve, - config.logger - ) + contents: + ( + await transformGlobImport( + contents, + path, + config.root, + resolve + ) + )?.s.toString() || contents } } else { scripts[key] = { @@ -467,20 +462,6 @@ function esbuildScanPlugin( config.optimizeDeps?.esbuildOptions?.loader?.[`.${ext}`] || (ext as Loader) - if (contents.includes('import.meta.glob')) { - return transformGlob( - contents, - id, - config.root, - loader, - resolve, - config.logger - ).then((contents) => ({ - loader, - contents - })) - } - return { loader, contents @@ -490,43 +471,6 @@ function esbuildScanPlugin( } } -async function transformGlob( - source: string, - importer: string, - root: string, - loader: Loader, - resolve: (url: string, importer?: string) => Promise, - logger: Logger -) { - // transform the content first since es-module-lexer can't handle non-js - if (loader !== 'js') { - source = (await transform(source, { loader })).code - } - - await init - const imports = parse(source)[0] - const s = new MagicString(source) - for (let index = 0; index < imports.length; index++) { - const { s: start, e: end, ss: expStart } = imports[index] - const url = source.slice(start, end) - if (url !== 'import.meta') continue - if (source.slice(end, end + 5) !== '.glob') continue - const { importsString, exp, endIndex } = await transformImportGlob( - source, - start, - normalizePath(importer), - index, - root, - logger, - undefined, - resolve - ) - s.prepend(importsString) - s.overwrite(expStart, endIndex, exp, { contentOnly: true }) - } - return s.toString() -} - /** * when using TS + (Vue + ` +
diff --git a/playground/css-codesplit/inline.css b/playground/css-codesplit/inline.css new file mode 100644 index 00000000000000..b2a2b5f1ead51f --- /dev/null +++ b/playground/css-codesplit/inline.css @@ -0,0 +1,3 @@ +.inline { + color: yellow; +} diff --git a/packages/playground/css-codesplit/main.css b/playground/css-codesplit/main.css similarity index 100% rename from packages/playground/css-codesplit/main.css rename to playground/css-codesplit/main.css diff --git a/playground/css-codesplit/main.js b/playground/css-codesplit/main.js new file mode 100644 index 00000000000000..eb6e703f79e718 --- /dev/null +++ b/playground/css-codesplit/main.js @@ -0,0 +1,15 @@ +import './style.css' +import './main.css' + +import('./async.css') + +import('./inline.css?inline').then((css) => { + document.querySelector('.dynamic-inline').textContent = css.default +}) + +import('./mod.module.css').then((css) => { + document.querySelector('.dynamic-module').textContent = JSON.stringify( + css.default + ) + document.querySelector('.mod').classList.add(css.default.mod) +}) diff --git a/playground/css-codesplit/mod.module.css b/playground/css-codesplit/mod.module.css new file mode 100644 index 00000000000000..7f84410485a32c --- /dev/null +++ b/playground/css-codesplit/mod.module.css @@ -0,0 +1,3 @@ +.mod { + color: yellow; +} diff --git a/packages/playground/css-codesplit/other.js b/playground/css-codesplit/other.js similarity index 100% rename from packages/playground/css-codesplit/other.js rename to playground/css-codesplit/other.js diff --git a/packages/playground/css-codesplit/package.json b/playground/css-codesplit/package.json similarity index 72% rename from packages/playground/css-codesplit/package.json rename to playground/css-codesplit/package.json index a4403ab0e47a2a..b6fe27f6d35759 100644 --- a/packages/playground/css-codesplit/package.json +++ b/playground/css-codesplit/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/css-codesplit/style.css b/playground/css-codesplit/style.css similarity index 100% rename from packages/playground/css-codesplit/style.css rename to playground/css-codesplit/style.css diff --git a/packages/playground/css-codesplit/vite.config.js b/playground/css-codesplit/vite.config.js similarity index 100% rename from packages/playground/css-codesplit/vite.config.js rename to playground/css-codesplit/vite.config.js diff --git a/playground/css-sourcemap/__tests__/build.spec.ts b/playground/css-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..b30284731a76d9 --- /dev/null +++ b/playground/css-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,7 @@ +import { isBuild, serverLogs } from '~utils' + +test.runIf(isBuild)('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) +}) diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/playground/css-sourcemap/__tests__/serve.spec.ts similarity index 63% rename from packages/playground/css-sourcemap/__tests__/serve.spec.ts rename to playground/css-sourcemap/__tests__/serve.spec.ts index 11e33a78af8424..730866d86ef03b 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/playground/css-sourcemap/__tests__/serve.spec.ts @@ -2,10 +2,12 @@ import { URL } from 'url' import { extractSourcemap, formatSourcemapForSnapshot, - isBuild -} from 'testUtils' + isServe, + page, + serverLogs +} from '~utils' -if (!isBuild) { +describe.runIf(isServe)('serve', () => { const getStyleTagContentIncluding = async (content: string) => { const styles = await page.$$('style') for (const style of styles) { @@ -17,68 +19,6 @@ if (!isBuild) { throw new Error('Not found') } - test('inline css', async () => { - const css = await getStyleTagContentIncluding('.inline ') - const map = extractSourcemap(css) - expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { - "mappings": "AAGO;AACP,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACf,CAAC,CAAC,CAAC;", - "sources": Array [ - "/root/index.html", - ], - "sourcesContent": Array [ - " - - - - -
-

CSS Sourcemap

- -

<inline>

- -

<linked>: no import

-

<linked>: with import

- -

<imported>: no import

-

<imported>: with import

- -

<imported sass>

-

<imported sass> with module

- -

<imported less> with string additionalData

- -

<imported stylus>

-
- - - - - ", - ], - "version": 3, - } - `) - }) - test('linked css', async () => { const res = await page.request.get( new URL('./linked.css', page.url()).href, @@ -89,8 +29,22 @@ if (!isBuild) { } ) const css = await res.text() - const lines = css.split('\n') - expect(lines[lines.length - 1].includes('/*')).toBe(false) // expect no sourcemap + const map = extractSourcemap(css) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + { + "mappings": "AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACT,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACb,CAAC;", + "sources": [ + "/root/linked.css", + ], + "sourcesContent": [ + ".linked { + color: red; + } + ", + ], + "version": 3, + } + `) }) test('linked css with import', async () => { @@ -105,13 +59,13 @@ if (!isBuild) { const css = await res.text() const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ", - "sources": Array [ + "sources": [ "/root/be-imported.css", "/root/linked-with-import.css", ], - "sourcesContent": Array [ + "sourcesContent": [ ".be-imported { color: red; } @@ -132,12 +86,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.imported ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACb,CAAC;", - "sources": Array [ + "sources": [ "/root/imported.css", ], - "sourcesContent": Array [ + "sourcesContent": [ ".imported { color: red; } @@ -152,13 +106,13 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.imported-with-import ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ", - "sources": Array [ + "sources": [ "/root/be-imported.css", "/root/imported-with-import.css", ], - "sourcesContent": Array [ + "sourcesContent": [ ".be-imported { color: red; } @@ -179,12 +133,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.imported-sass ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AACE;EACE", - "sources": Array [ + "sources": [ "/root/imported.sass", ], - "sourcesContent": Array [ + "sourcesContent": [ ".imported &-sass color: red @@ -199,12 +153,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('._imported-sass-module_') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AACE;EACE", - "sources": Array [ + "sources": [ "/root/imported.module.sass", ], - "sourcesContent": Array [ + "sourcesContent": [ ".imported &-sass-module color: red @@ -219,12 +173,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.imported-less ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AACE;EACE", - "sources": Array [ + "sources": [ "/root/imported.less", ], - "sourcesContent": Array [ + "sourcesContent": [ ".imported { &-less { color: @color; @@ -241,12 +195,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.imported-stylus ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AACE;EACE,cAAM", - "sources": Array [ + "sources": [ "/root/imported.styl", ], - "sourcesContent": Array [ + "sourcesContent": [ ".imported &-stylus color blue-red-mixed @@ -262,8 +216,4 @@ if (!isBuild) { expect(log).not.toMatch(/Sourcemap for .+ points to missing source files/) }) }) -} else { - test('this file only includes test for serve', () => { - expect(true).toBe(true) - }) -} +}) diff --git a/packages/playground/css-sourcemap/be-imported.css b/playground/css-sourcemap/be-imported.css similarity index 100% rename from packages/playground/css-sourcemap/be-imported.css rename to playground/css-sourcemap/be-imported.css diff --git a/packages/playground/css-sourcemap/imported-with-import.css b/playground/css-sourcemap/imported-with-import.css similarity index 100% rename from packages/playground/css-sourcemap/imported-with-import.css rename to playground/css-sourcemap/imported-with-import.css diff --git a/packages/playground/css-sourcemap/imported.css b/playground/css-sourcemap/imported.css similarity index 100% rename from packages/playground/css-sourcemap/imported.css rename to playground/css-sourcemap/imported.css diff --git a/packages/playground/css-sourcemap/imported.less b/playground/css-sourcemap/imported.less similarity index 100% rename from packages/playground/css-sourcemap/imported.less rename to playground/css-sourcemap/imported.less diff --git a/packages/playground/css-sourcemap/imported.module.sass b/playground/css-sourcemap/imported.module.sass similarity index 100% rename from packages/playground/css-sourcemap/imported.module.sass rename to playground/css-sourcemap/imported.module.sass diff --git a/packages/playground/css-sourcemap/imported.sass b/playground/css-sourcemap/imported.sass similarity index 100% rename from packages/playground/css-sourcemap/imported.sass rename to playground/css-sourcemap/imported.sass diff --git a/packages/playground/css-sourcemap/imported.styl b/playground/css-sourcemap/imported.styl similarity index 100% rename from packages/playground/css-sourcemap/imported.styl rename to playground/css-sourcemap/imported.styl diff --git a/packages/playground/css-sourcemap/index.html b/playground/css-sourcemap/index.html similarity index 100% rename from packages/playground/css-sourcemap/index.html rename to playground/css-sourcemap/index.html diff --git a/packages/playground/css-sourcemap/linked-with-import.css b/playground/css-sourcemap/linked-with-import.css similarity index 100% rename from packages/playground/css-sourcemap/linked-with-import.css rename to playground/css-sourcemap/linked-with-import.css diff --git a/packages/playground/css-sourcemap/linked.css b/playground/css-sourcemap/linked.css similarity index 100% rename from packages/playground/css-sourcemap/linked.css rename to playground/css-sourcemap/linked.css diff --git a/packages/playground/css-sourcemap/package.json b/playground/css-sourcemap/package.json similarity index 67% rename from packages/playground/css-sourcemap/package.json rename to playground/css-sourcemap/package.json index c7e9e61372cefa..6c0212efa74155 100644 --- a/packages/playground/css-sourcemap/package.json +++ b/playground/css-sourcemap/package.json @@ -5,13 +5,13 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "devDependencies": { "less": "^4.1.2", - "magic-string": "^0.25.7", - "sass": "^1.43.4", + "magic-string": "^0.25.9", + "sass": "^1.51.0", "stylus": "^0.55.0" } } diff --git a/packages/playground/css-sourcemap/vite.config.js b/playground/css-sourcemap/vite.config.js similarity index 100% rename from packages/playground/css-sourcemap/vite.config.js rename to playground/css-sourcemap/vite.config.js diff --git a/packages/playground/css/__tests__/css.spec.ts b/playground/css/__tests__/css.spec.ts similarity index 94% rename from packages/playground/css/__tests__/css.spec.ts rename to playground/css/__tests__/css.spec.ts index 6ca00e760349b1..5341522900ddb1 100644 --- a/packages/playground/css/__tests__/css.spec.ts +++ b/playground/css/__tests__/css.spec.ts @@ -1,21 +1,24 @@ -import fs from 'fs' -import path from 'path' import { editFile, findAssetFile, getBg, getColor, isBuild, + page, removeFile, - testDir, + serverLogs, untilUpdated -} from '../../testUtils' +} from '~utils' // note: tests should retrieve the element at the beginning of test and reuse it // in later assertions to ensure CSS HMR doesn't reload the page test('imported css', async () => { const css = await page.textContent('.imported-css') - expect(css).toContain('.imported {') + expect(css).toMatch(/\.imported ?{/) + if (isBuild) { + expect(css.trim()).not.toContain('\n') // check minified + } + const glob = await page.textContent('.imported-css-glob') expect(glob).toContain('.dir-import') const globEager = await page.textContent('.imported-css-globEager') @@ -247,14 +250,12 @@ test('inline css modules', async () => { expect(css).toMatch(/\.inline-module__apply-color-inline___[\w-]{5}/) }) -if (isBuild) { - test('@charset hoist', async () => { - serverLogs.forEach((log) => { - // no warning from esbuild css minifier - expect(log).not.toMatch('"@charset" must be the first rule in the file') - }) +test.runIf(isBuild)('@charset hoist', async () => { + serverLogs.forEach((log) => { + // no warning from esbuild css minifier + expect(log).not.toMatch('"@charset" must be the first rule in the file') }) -} +}) test('@import dependency w/ style entry', async () => { expect(await getColor('.css-dep')).toBe('purple') @@ -372,6 +373,10 @@ test('inlined-code', async () => { // should resolve assets expect(code).toContain('background:') expect(code).not.toContain('__VITE_ASSET__') + + if (isBuild) { + expect(code.trim()).not.toContain('\n') // check minified + } }) test('minify css', async () => { @@ -405,3 +410,13 @@ test("relative path rewritten in Less's data-uri", async () => { /^url\("data:image\/svg\+xml,%3Csvg/ ) }) + +test('PostCSS source.input.from includes query', async () => { + const code = await page.textContent('.postcss-source-input') + // should resolve assets + expect(code).toContain( + isBuild + ? '/postcss-source-input.css?used&query=foo' + : '/postcss-source-input.css?query=foo' + ) +}) diff --git a/packages/playground/css/__tests__/postcss-plugins-different-dir.spec.ts b/playground/css/__tests__/postcss-plugins-different-dir.spec.ts similarity index 93% rename from packages/playground/css/__tests__/postcss-plugins-different-dir.spec.ts rename to playground/css/__tests__/postcss-plugins-different-dir.spec.ts index 8bedc26ee354c8..55a6d8fe8dd130 100644 --- a/packages/playground/css/__tests__/postcss-plugins-different-dir.spec.ts +++ b/playground/css/__tests__/postcss-plugins-different-dir.spec.ts @@ -1,6 +1,6 @@ -import { getColor, getBgColor, ports } from '../../testUtils' -import { createServer } from 'vite' import path from 'path' +import { createServer } from 'vite' +import { getBgColor, getColor, page, ports } from '~utils' // Regression test for https://github.com/vitejs/vite/issues/4000 test('postcss plugins in different dir', async () => { diff --git a/packages/playground/css/async-treeshaken.css b/playground/css/async-treeshaken.css similarity index 100% rename from packages/playground/css/async-treeshaken.css rename to playground/css/async-treeshaken.css diff --git a/packages/playground/css/async-treeshaken.js b/playground/css/async-treeshaken.js similarity index 100% rename from packages/playground/css/async-treeshaken.js rename to playground/css/async-treeshaken.js diff --git a/packages/playground/css/async.css b/playground/css/async.css similarity index 100% rename from packages/playground/css/async.css rename to playground/css/async.css diff --git a/packages/playground/css/async.js b/playground/css/async.js similarity index 100% rename from packages/playground/css/async.js rename to playground/css/async.js diff --git a/packages/playground/css/charset.css b/playground/css/charset.css similarity index 100% rename from packages/playground/css/charset.css rename to playground/css/charset.css diff --git a/packages/playground/css/composed.module.css b/playground/css/composed.module.css similarity index 100% rename from packages/playground/css/composed.module.css rename to playground/css/composed.module.css diff --git a/packages/playground/css/composed.module.less b/playground/css/composed.module.less similarity index 100% rename from packages/playground/css/composed.module.less rename to playground/css/composed.module.less diff --git a/packages/playground/css/composed.module.scss b/playground/css/composed.module.scss similarity index 100% rename from packages/playground/css/composed.module.scss rename to playground/css/composed.module.scss diff --git a/packages/playground/css/composes-path-resolving.module.css b/playground/css/composes-path-resolving.module.css similarity index 100% rename from packages/playground/css/composes-path-resolving.module.css rename to playground/css/composes-path-resolving.module.css diff --git a/packages/playground/css/css-dep/index.css b/playground/css/css-dep/index.css similarity index 100% rename from packages/playground/css/css-dep/index.css rename to playground/css/css-dep/index.css diff --git a/packages/playground/css/css-dep/index.js b/playground/css/css-dep/index.js similarity index 100% rename from packages/playground/css/css-dep/index.js rename to playground/css/css-dep/index.js diff --git a/packages/playground/css/css-dep/index.scss b/playground/css/css-dep/index.scss similarity index 100% rename from packages/playground/css/css-dep/index.scss rename to playground/css/css-dep/index.scss diff --git a/packages/playground/css/css-dep/index.styl b/playground/css/css-dep/index.styl similarity index 100% rename from packages/playground/css/css-dep/index.styl rename to playground/css/css-dep/index.styl diff --git a/packages/playground/css/css-dep/package.json b/playground/css/css-dep/package.json similarity index 100% rename from packages/playground/css/css-dep/package.json rename to playground/css/css-dep/package.json diff --git a/packages/playground/css/dep.css b/playground/css/dep.css similarity index 100% rename from packages/playground/css/dep.css rename to playground/css/dep.css diff --git a/packages/playground/css/folder with space/ok.png b/playground/css/folder with space/ok.png similarity index 100% rename from packages/playground/css/folder with space/ok.png rename to playground/css/folder with space/ok.png diff --git a/packages/playground/css/folder with space/space.css b/playground/css/folder with space/space.css similarity index 100% rename from packages/playground/css/folder with space/space.css rename to playground/css/folder with space/space.css diff --git a/packages/playground/css/glob-dep.css b/playground/css/glob-dep.css similarity index 100% rename from packages/playground/css/glob-dep.css rename to playground/css/glob-dep.css diff --git a/packages/playground/css/glob-dep/bar.css b/playground/css/glob-dep/bar.css similarity index 100% rename from packages/playground/css/glob-dep/bar.css rename to playground/css/glob-dep/bar.css diff --git a/packages/playground/css/glob-dep/foo.css b/playground/css/glob-dep/foo.css similarity index 100% rename from packages/playground/css/glob-dep/foo.css rename to playground/css/glob-dep/foo.css diff --git a/packages/playground/css/glob-import/bar.css b/playground/css/glob-import/bar.css similarity index 100% rename from packages/playground/css/glob-import/bar.css rename to playground/css/glob-import/bar.css diff --git a/packages/playground/css/glob-import/foo.css b/playground/css/glob-import/foo.css similarity index 100% rename from packages/playground/css/glob-import/foo.css rename to playground/css/glob-import/foo.css diff --git a/packages/playground/css/imported-at-import.css b/playground/css/imported-at-import.css similarity index 100% rename from packages/playground/css/imported-at-import.css rename to playground/css/imported-at-import.css diff --git a/packages/playground/css/imported.css b/playground/css/imported.css similarity index 100% rename from packages/playground/css/imported.css rename to playground/css/imported.css diff --git a/packages/playground/css/index.html b/playground/css/index.html similarity index 97% rename from packages/playground/css/index.html rename to playground/css/index.html index fef6a0be393748..15e81192cec7f1 100644 --- a/packages/playground/css/index.html +++ b/playground/css/index.html @@ -135,6 +135,9 @@

CSS

Raw Support


+
+  

PostCSS source.input.from. Should include query

+

 
 
 
diff --git a/packages/playground/css/inline.module.css b/playground/css/inline.module.css
similarity index 100%
rename from packages/playground/css/inline.module.css
rename to playground/css/inline.module.css
diff --git a/packages/playground/css/inlined.css b/playground/css/inlined.css
similarity index 100%
rename from packages/playground/css/inlined.css
rename to playground/css/inlined.css
diff --git a/packages/playground/css/less.less b/playground/css/less.less
similarity index 100%
rename from packages/playground/css/less.less
rename to playground/css/less.less
diff --git a/packages/playground/css/less/components/form.less b/playground/css/less/components/form.less
similarity index 100%
rename from packages/playground/css/less/components/form.less
rename to playground/css/less/components/form.less
diff --git a/packages/playground/css/less/images/backgrounds/form-select.svg b/playground/css/less/images/backgrounds/form-select.svg
similarity index 100%
rename from packages/playground/css/less/images/backgrounds/form-select.svg
rename to playground/css/less/images/backgrounds/form-select.svg
diff --git a/packages/playground/css/linked-at-import.css b/playground/css/linked-at-import.css
similarity index 100%
rename from packages/playground/css/linked-at-import.css
rename to playground/css/linked-at-import.css
diff --git a/packages/playground/css/linked.css b/playground/css/linked.css
similarity index 100%
rename from packages/playground/css/linked.css
rename to playground/css/linked.css
diff --git a/packages/playground/css/main.js b/playground/css/main.js
similarity index 89%
rename from packages/playground/css/main.js
rename to playground/css/main.js
index 0d03aafbf0ec7f..90f74c96793c55 100644
--- a/packages/playground/css/main.js
+++ b/playground/css/main.js
@@ -80,10 +80,15 @@ text('.inlined-code', inlined)
 
 // glob
 const glob = import.meta.glob('./glob-import/*.css')
-Promise.all(Object.keys(glob).map((key) => glob[key]())).then((res) => {
+Promise.all(
+  Object.keys(glob).map((key) => glob[key]().then((i) => i.default))
+).then((res) => {
   text('.imported-css-glob', JSON.stringify(res, null, 2))
 })
 
 // globEager
-const globEager = import.meta.globEager('./glob-import/*.css')
+const globEager = import.meta.glob('./glob-import/*.css', { eager: true })
 text('.imported-css-globEager', JSON.stringify(globEager, null, 2))
+
+import postcssSourceInput from './postcss-source-input.css?query=foo'
+text('.postcss-source-input', postcssSourceInput)
diff --git a/packages/playground/css/minify.css b/playground/css/minify.css
similarity index 100%
rename from packages/playground/css/minify.css
rename to playground/css/minify.css
diff --git a/packages/playground/css/mod.module.css b/playground/css/mod.module.css
similarity index 100%
rename from packages/playground/css/mod.module.css
rename to playground/css/mod.module.css
diff --git a/packages/playground/css/mod.module.scss b/playground/css/mod.module.scss
similarity index 100%
rename from packages/playground/css/mod.module.scss
rename to playground/css/mod.module.scss
diff --git a/packages/playground/css/nested/_index.scss b/playground/css/nested/_index.scss
similarity index 100%
rename from packages/playground/css/nested/_index.scss
rename to playground/css/nested/_index.scss
diff --git a/packages/playground/css/nested/_partial.scss b/playground/css/nested/_partial.scss
similarity index 100%
rename from packages/playground/css/nested/_partial.scss
rename to playground/css/nested/_partial.scss
diff --git a/packages/playground/css/nested/css-in-less-2.less b/playground/css/nested/css-in-less-2.less
similarity index 100%
rename from packages/playground/css/nested/css-in-less-2.less
rename to playground/css/nested/css-in-less-2.less
diff --git a/packages/playground/css/nested/css-in-less.css b/playground/css/nested/css-in-less.css
similarity index 100%
rename from packages/playground/css/nested/css-in-less.css
rename to playground/css/nested/css-in-less.css
diff --git a/packages/playground/css/nested/css-in-less.less b/playground/css/nested/css-in-less.less
similarity index 100%
rename from packages/playground/css/nested/css-in-less.less
rename to playground/css/nested/css-in-less.less
diff --git a/packages/playground/css/nested/css-in-scss.css b/playground/css/nested/css-in-scss.css
similarity index 100%
rename from packages/playground/css/nested/css-in-scss.css
rename to playground/css/nested/css-in-scss.css
diff --git a/packages/playground/css/nested/icon.png b/playground/css/nested/icon.png
similarity index 100%
rename from packages/playground/css/nested/icon.png
rename to playground/css/nested/icon.png
diff --git a/packages/playground/css/nested/nested.less b/playground/css/nested/nested.less
similarity index 100%
rename from packages/playground/css/nested/nested.less
rename to playground/css/nested/nested.less
diff --git a/packages/playground/css/nested/nested.styl b/playground/css/nested/nested.styl
similarity index 100%
rename from packages/playground/css/nested/nested.styl
rename to playground/css/nested/nested.styl
diff --git a/packages/playground/css/ok.png b/playground/css/ok.png
similarity index 100%
rename from packages/playground/css/ok.png
rename to playground/css/ok.png
diff --git a/packages/playground/css/options/absolute-import.styl b/playground/css/options/absolute-import.styl
similarity index 100%
rename from packages/playground/css/options/absolute-import.styl
rename to playground/css/options/absolute-import.styl
diff --git a/packages/playground/css/options/relative-import.styl b/playground/css/options/relative-import.styl
similarity index 100%
rename from packages/playground/css/options/relative-import.styl
rename to playground/css/options/relative-import.styl
diff --git a/packages/playground/css/package.json b/playground/css/package.json
similarity index 79%
rename from packages/playground/css/package.json
rename to playground/css/package.json
index b45063100be089..daaad66a9bb41f 100644
--- a/packages/playground/css/package.json
+++ b/playground/css/package.json
@@ -5,7 +5,7 @@
   "scripts": {
     "dev": "vite",
     "build": "vite build",
-    "debug": "node --inspect-brk ../../vite/bin/vite",
+    "debug": "node --inspect-brk ../../packages/vite/bin/vite",
     "preview": "vite preview"
   },
   "devDependencies": {
@@ -13,7 +13,7 @@
     "fast-glob": "^3.2.11",
     "less": "^4.1.2",
     "postcss-nested": "^5.0.6",
-    "sass": "^1.43.4",
+    "sass": "^1.51.0",
     "stylus": "^0.55.0"
   }
 }
diff --git a/packages/playground/css/pkg-dep/_index.scss b/playground/css/pkg-dep/_index.scss
similarity index 100%
rename from packages/playground/css/pkg-dep/_index.scss
rename to playground/css/pkg-dep/_index.scss
diff --git a/packages/playground/css/pkg-dep/index.js b/playground/css/pkg-dep/index.js
similarity index 100%
rename from packages/playground/css/pkg-dep/index.js
rename to playground/css/pkg-dep/index.js
diff --git a/packages/playground/css/pkg-dep/package.json b/playground/css/pkg-dep/package.json
similarity index 100%
rename from packages/playground/css/pkg-dep/package.json
rename to playground/css/pkg-dep/package.json
diff --git a/packages/playground/css/postcss-caching/blue-app/imported.css b/playground/css/postcss-caching/blue-app/imported.css
similarity index 100%
rename from packages/playground/css/postcss-caching/blue-app/imported.css
rename to playground/css/postcss-caching/blue-app/imported.css
diff --git a/packages/playground/css/postcss-caching/blue-app/index.html b/playground/css/postcss-caching/blue-app/index.html
similarity index 100%
rename from packages/playground/css/postcss-caching/blue-app/index.html
rename to playground/css/postcss-caching/blue-app/index.html
diff --git a/packages/playground/css/postcss-caching/blue-app/main.js b/playground/css/postcss-caching/blue-app/main.js
similarity index 100%
rename from packages/playground/css/postcss-caching/blue-app/main.js
rename to playground/css/postcss-caching/blue-app/main.js
diff --git a/packages/playground/css/postcss-caching/blue-app/package.json b/playground/css/postcss-caching/blue-app/package.json
similarity index 71%
rename from packages/playground/css/postcss-caching/blue-app/package.json
rename to playground/css/postcss-caching/blue-app/package.json
index 34be8916bb2c9e..82ba64fadd44b4 100644
--- a/packages/playground/css/postcss-caching/blue-app/package.json
+++ b/playground/css/postcss-caching/blue-app/package.json
@@ -5,7 +5,7 @@
   "scripts": {
     "dev": "vite",
     "build": "vite build",
-    "debug": "node --inspect-brk ../../vite/bin/vite",
+    "debug": "node --inspect-brk ../../packages/vite/bin/vite",
     "preview": "vite preview"
   }
 }
diff --git a/packages/playground/css/postcss-caching/blue-app/postcss.config.js b/playground/css/postcss-caching/blue-app/postcss.config.js
similarity index 100%
rename from packages/playground/css/postcss-caching/blue-app/postcss.config.js
rename to playground/css/postcss-caching/blue-app/postcss.config.js
diff --git a/packages/playground/css/postcss-caching/css.spec.ts b/playground/css/postcss-caching/css.spec.ts
similarity index 96%
rename from packages/playground/css/postcss-caching/css.spec.ts
rename to playground/css/postcss-caching/css.spec.ts
index e8ba73154b6bc8..bbffdb618280e4 100644
--- a/packages/playground/css/postcss-caching/css.spec.ts
+++ b/playground/css/postcss-caching/css.spec.ts
@@ -1,4 +1,4 @@
-import { getColor, ports } from '../../testUtils'
+import { getColor, page, ports } from '~utils'
 import { createServer } from 'vite'
 import path from 'path'
 
diff --git a/packages/playground/css/postcss-caching/green-app/imported.css b/playground/css/postcss-caching/green-app/imported.css
similarity index 100%
rename from packages/playground/css/postcss-caching/green-app/imported.css
rename to playground/css/postcss-caching/green-app/imported.css
diff --git a/packages/playground/css/postcss-caching/green-app/index.html b/playground/css/postcss-caching/green-app/index.html
similarity index 100%
rename from packages/playground/css/postcss-caching/green-app/index.html
rename to playground/css/postcss-caching/green-app/index.html
diff --git a/packages/playground/css/postcss-caching/green-app/main.js b/playground/css/postcss-caching/green-app/main.js
similarity index 100%
rename from packages/playground/css/postcss-caching/green-app/main.js
rename to playground/css/postcss-caching/green-app/main.js
diff --git a/packages/playground/css/postcss-caching/green-app/package.json b/playground/css/postcss-caching/green-app/package.json
similarity index 71%
rename from packages/playground/css/postcss-caching/green-app/package.json
rename to playground/css/postcss-caching/green-app/package.json
index 947b30384a1a53..72bd0f45b8865f 100644
--- a/packages/playground/css/postcss-caching/green-app/package.json
+++ b/playground/css/postcss-caching/green-app/package.json
@@ -5,7 +5,7 @@
   "scripts": {
     "dev": "vite",
     "build": "vite build",
-    "debug": "node --inspect-brk ../../vite/bin/vite",
+    "debug": "node --inspect-brk ../../packages/vite/bin/vite",
     "preview": "vite preview"
   }
 }
diff --git a/packages/playground/css/postcss-caching/green-app/postcss.config.js b/playground/css/postcss-caching/green-app/postcss.config.js
similarity index 100%
rename from packages/playground/css/postcss-caching/green-app/postcss.config.js
rename to playground/css/postcss-caching/green-app/postcss.config.js
diff --git a/playground/css/postcss-source-input.css b/playground/css/postcss-source-input.css
new file mode 100644
index 00000000000000..c6c3cb0c16dece
--- /dev/null
+++ b/playground/css/postcss-source-input.css
@@ -0,0 +1 @@
+@source-input;
diff --git a/packages/playground/css/postcss.config.js b/playground/css/postcss.config.js
similarity index 68%
rename from packages/playground/css/postcss.config.js
rename to playground/css/postcss.config.js
index f3d6ac9548b6a9..33058023541515 100644
--- a/packages/playground/css/postcss.config.js
+++ b/playground/css/postcss.config.js
@@ -1,5 +1,5 @@
 module.exports = {
-  plugins: [require('postcss-nested'), testDirDep]
+  plugins: [require('postcss-nested'), testDirDep, testSourceInput]
 }
 
 const fs = require('fs')
@@ -35,3 +35,20 @@ function testDirDep() {
   }
 }
 testDirDep.postcss = true
+
+function testSourceInput() {
+  return {
+    postcssPlugin: 'source-input',
+    AtRule(atRule) {
+      if (atRule.name === 'source-input') {
+        atRule.after(
+          `.source-input::before { content: ${JSON.stringify(
+            atRule.source.input.from
+          )}; }`
+        )
+        atRule.remove()
+      }
+    }
+  }
+}
+testSourceInput.postcss = true
diff --git a/packages/playground/css/raw-imported.css b/playground/css/raw-imported.css
similarity index 100%
rename from packages/playground/css/raw-imported.css
rename to playground/css/raw-imported.css
diff --git a/packages/playground/css/sass.scss b/playground/css/sass.scss
similarity index 100%
rename from packages/playground/css/sass.scss
rename to playground/css/sass.scss
diff --git a/packages/playground/css/stylus.styl b/playground/css/stylus.styl
similarity index 100%
rename from packages/playground/css/stylus.styl
rename to playground/css/stylus.styl
diff --git a/packages/playground/css/vite.config.js b/playground/css/vite.config.js
similarity index 100%
rename from packages/playground/css/vite.config.js
rename to playground/css/vite.config.js
diff --git a/playground/data-uri/__tests__/data-uri.spec.ts b/playground/data-uri/__tests__/data-uri.spec.ts
new file mode 100644
index 00000000000000..4b7f3d6e1e471b
--- /dev/null
+++ b/playground/data-uri/__tests__/data-uri.spec.ts
@@ -0,0 +1,14 @@
+import { findAssetFile, isBuild, page } from '~utils'
+
+test('plain', async () => {
+  expect(await page.textContent('.plain')).toBe('hi')
+})
+
+test('base64', async () => {
+  expect(await page.textContent('.base64')).toBe('hi')
+})
+
+test.runIf(isBuild)('should compile away the import for build', async () => {
+  const file = findAssetFile('index')
+  expect(file).not.toMatch('import')
+})
diff --git a/packages/playground/data-uri/index.html b/playground/data-uri/index.html
similarity index 100%
rename from packages/playground/data-uri/index.html
rename to playground/data-uri/index.html
diff --git a/packages/playground/data-uri/package.json b/playground/data-uri/package.json
similarity index 72%
rename from packages/playground/data-uri/package.json
rename to playground/data-uri/package.json
index a07c9a2cd6a663..4d30ad97b9acbb 100644
--- a/packages/playground/data-uri/package.json
+++ b/playground/data-uri/package.json
@@ -5,7 +5,7 @@
   "scripts": {
     "dev": "vite",
     "build": "vite build",
-    "debug": "node --inspect-brk ../../vite/bin/vite",
+    "debug": "node --inspect-brk ../../packages/vite/bin/vite",
     "preview": "vite preview"
   }
 }
diff --git a/packages/playground/define/__tests__/define.spec.ts b/playground/define/__tests__/define.spec.ts
similarity index 64%
rename from packages/playground/define/__tests__/define.spec.ts
rename to playground/define/__tests__/define.spec.ts
index 709f7a935dc8c1..b2eb571734cc54 100644
--- a/packages/playground/define/__tests__/define.spec.ts
+++ b/playground/define/__tests__/define.spec.ts
@@ -1,10 +1,16 @@
+import viteConfig from '../vite.config'
+import { page } from '~utils'
+
 test('string', async () => {
-  const defines = require('../vite.config.js').define
+  const defines = viteConfig.define
 
-  expect(await page.textContent('.exp')).toBe(String(eval(defines.__EXP__)))
+  expect(await page.textContent('.exp')).toBe(
+    String(typeof eval(defines.__EXP__))
+  )
   expect(await page.textContent('.string')).toBe(JSON.parse(defines.__STRING__))
   expect(await page.textContent('.number')).toBe(String(defines.__NUMBER__))
   expect(await page.textContent('.boolean')).toBe(String(defines.__BOOLEAN__))
+
   expect(await page.textContent('.object')).toBe(
     JSON.stringify(defines.__OBJ__, null, 2)
   )
@@ -20,6 +26,14 @@ test('string', async () => {
   expect(await page.textContent('.spread-array')).toBe(
     JSON.stringify([...defines.__STRING__])
   )
+  expect(await page.textContent('.dollar-identifier')).toBe(
+    String(defines.$DOLLAR)
+  )
+  expect(await page.textContent('.unicode-identifier')).toBe(
+    String(defines.ÖUNICODE_LETTERɵ)
+  )
+  expect(await page.textContent('.no-identifier-substring')).toBe(String(true))
+  expect(await page.textContent('.no-property')).toBe(String(true))
   // html would't need to define replacement
   expect(await page.textContent('.exp-define')).toBe('__EXP__')
   expect(await page.textContent('.import-json')).toBe('__EXP__')
diff --git a/packages/playground/define/data.json b/playground/define/data.json
similarity index 100%
rename from packages/playground/define/data.json
rename to playground/define/data.json
diff --git a/packages/playground/define/index.html b/playground/define/index.html
similarity index 68%
rename from packages/playground/define/index.html
rename to playground/define/index.html
index da78d192216b11..97a7b9902a1dcb 100644
--- a/packages/playground/define/index.html
+++ b/playground/define/index.html
@@ -9,12 +9,16 @@ 

Define

process as property:

spread object:

spread array:

+

dollar identifier:

+

unicode identifier:

+

no property:

+

no identifier substring:

define variable in html: __EXP__

import json:

+ diff --git a/packages/playground/dynamic-import/mxd.js b/playground/dynamic-import/mxd.js similarity index 100% rename from packages/playground/dynamic-import/mxd.js rename to playground/dynamic-import/mxd.js diff --git a/packages/playground/dynamic-import/mxd.json b/playground/dynamic-import/mxd.json similarity index 100% rename from packages/playground/dynamic-import/mxd.json rename to playground/dynamic-import/mxd.json diff --git a/playground/dynamic-import/nested/deps.js b/playground/dynamic-import/nested/deps.js new file mode 100644 index 00000000000000..88fd4787941fd0 --- /dev/null +++ b/playground/dynamic-import/nested/deps.js @@ -0,0 +1,3 @@ +/* don't include dynamic import inside this file */ + +import 'pkg' diff --git a/playground/dynamic-import/nested/hello.js b/playground/dynamic-import/nested/hello.js new file mode 100644 index 00000000000000..67900ef0999962 --- /dev/null +++ b/playground/dynamic-import/nested/hello.js @@ -0,0 +1,3 @@ +export function hello() { + return 'hello' +} diff --git a/packages/playground/dynamic-import/nested/index.js b/playground/dynamic-import/nested/index.js similarity index 82% rename from packages/playground/dynamic-import/nested/index.js rename to playground/dynamic-import/nested/index.js index 5518c56a35a2cc..61f817ce7dd7bc 100644 --- a/packages/playground/dynamic-import/nested/index.js +++ b/playground/dynamic-import/nested/index.js @@ -70,6 +70,25 @@ document.querySelector('.css').addEventListener('click', async () => { text('.view', 'dynamic import css') }) +document.querySelector('.pkg-css').addEventListener('click', async () => { + await import('./deps') + text('.view', 'dynamic import css in package') +}) + function text(el, text) { document.querySelector(el).textContent = text } + +const base = 'hello' + +import(`../alias/${base}.js`).then((mod) => { + text('.dynamic-import-with-vars', mod.hello()) +}) + +import(`@/${base}.js`).then((mod) => { + text('.dynamic-import-with-vars-alias', mod.hello()) +}) + +import(`../alias/${base}.js?raw`).then((mod) => { + text('.dynamic-import-with-vars-raw', JSON.stringify(mod)) +}) diff --git a/packages/playground/dynamic-import/nested/shared.js b/playground/dynamic-import/nested/shared.js similarity index 100% rename from packages/playground/dynamic-import/nested/shared.js rename to playground/dynamic-import/nested/shared.js diff --git a/playground/dynamic-import/package.json b/playground/dynamic-import/package.json new file mode 100644 index 00000000000000..9492fc0173e2c2 --- /dev/null +++ b/playground/dynamic-import/package.json @@ -0,0 +1,15 @@ +{ + "name": "test-dynamic-import", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", + "preview": "vite preview", + "postinstall": "ts-node ../../scripts/patchFileDeps.ts" + }, + "dependencies": { + "pkg": "file:./pkg" + } +} diff --git a/playground/dynamic-import/pkg/index.js b/playground/dynamic-import/pkg/index.js new file mode 100644 index 00000000000000..20f705c0b4a8c9 --- /dev/null +++ b/playground/dynamic-import/pkg/index.js @@ -0,0 +1 @@ +import('./pkg.css') diff --git a/playground/dynamic-import/pkg/package.json b/playground/dynamic-import/pkg/package.json new file mode 100644 index 00000000000000..1eab564572e245 --- /dev/null +++ b/playground/dynamic-import/pkg/package.json @@ -0,0 +1,7 @@ +{ + "name": "pkg", + "type": "module", + "private": true, + "version": "1.0.0", + "main": "index.js" +} diff --git a/playground/dynamic-import/pkg/pkg.css b/playground/dynamic-import/pkg/pkg.css new file mode 100644 index 00000000000000..349d669b6829bf --- /dev/null +++ b/playground/dynamic-import/pkg/pkg.css @@ -0,0 +1,3 @@ +.pkg-css { + color: blue; +} diff --git a/packages/playground/dynamic-import/qux.js b/playground/dynamic-import/qux.js similarity index 100% rename from packages/playground/dynamic-import/qux.js rename to playground/dynamic-import/qux.js diff --git a/packages/playground/dynamic-import/views/bar.js b/playground/dynamic-import/views/bar.js similarity index 100% rename from packages/playground/dynamic-import/views/bar.js rename to playground/dynamic-import/views/bar.js diff --git a/packages/playground/dynamic-import/views/baz.js b/playground/dynamic-import/views/baz.js similarity index 100% rename from packages/playground/dynamic-import/views/baz.js rename to playground/dynamic-import/views/baz.js diff --git a/packages/playground/dynamic-import/views/foo.js b/playground/dynamic-import/views/foo.js similarity index 100% rename from packages/playground/dynamic-import/views/foo.js rename to playground/dynamic-import/views/foo.js diff --git a/packages/playground/dynamic-import/vite.config.js b/playground/dynamic-import/vite.config.js similarity index 77% rename from packages/playground/dynamic-import/vite.config.js rename to playground/dynamic-import/vite.config.js index 010e47d6308d30..50b90639fddd7f 100644 --- a/packages/playground/dynamic-import/vite.config.js +++ b/playground/dynamic-import/vite.config.js @@ -1,7 +1,8 @@ const fs = require('fs') const path = require('path') +const vite = require('vite') -module.exports = { +module.exports = vite.defineConfig({ plugins: [ { name: 'copy', @@ -20,5 +21,10 @@ module.exports = { ) } } - ] -} + ], + resolve: { + alias: { + '@': path.resolve(__dirname, 'alias') + } + } +}) diff --git a/packages/playground/env-nested/.env b/playground/env-nested/.env similarity index 100% rename from packages/playground/env-nested/.env rename to playground/env-nested/.env diff --git a/packages/playground/env-nested/__tests__/env-nested.spec.ts b/playground/env-nested/__tests__/env-nested.spec.ts similarity index 90% rename from packages/playground/env-nested/__tests__/env-nested.spec.ts rename to playground/env-nested/__tests__/env-nested.spec.ts index 1ceebde7a044b7..2ae9ab64023896 100644 --- a/packages/playground/env-nested/__tests__/env-nested.spec.ts +++ b/playground/env-nested/__tests__/env-nested.spec.ts @@ -1,4 +1,4 @@ -import { isBuild } from 'testUtils' +import { isBuild, page } from '~utils' const mode = isBuild ? `production` : `development` diff --git a/packages/playground/env-nested/envs/.env.development b/playground/env-nested/envs/.env.development similarity index 100% rename from packages/playground/env-nested/envs/.env.development rename to playground/env-nested/envs/.env.development diff --git a/packages/playground/env-nested/envs/.env.production b/playground/env-nested/envs/.env.production similarity index 100% rename from packages/playground/env-nested/envs/.env.production rename to playground/env-nested/envs/.env.production diff --git a/packages/playground/env-nested/index.html b/playground/env-nested/index.html similarity index 100% rename from packages/playground/env-nested/index.html rename to playground/env-nested/index.html diff --git a/packages/playground/env-nested/package.json b/playground/env-nested/package.json similarity index 72% rename from packages/playground/env-nested/package.json rename to playground/env-nested/package.json index 8fecc69a41c2f4..530b4e621005b0 100644 --- a/packages/playground/env-nested/package.json +++ b/playground/env-nested/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/env-nested/vite.config.js b/playground/env-nested/vite.config.js similarity index 100% rename from packages/playground/env-nested/vite.config.js rename to playground/env-nested/vite.config.js diff --git a/packages/playground/env/.env b/playground/env/.env similarity index 100% rename from packages/playground/env/.env rename to playground/env/.env diff --git a/packages/playground/env/.env.development b/playground/env/.env.development similarity index 100% rename from packages/playground/env/.env.development rename to playground/env/.env.development diff --git a/packages/playground/env/.env.production b/playground/env/.env.production similarity index 100% rename from packages/playground/env/.env.production rename to playground/env/.env.production diff --git a/packages/playground/env/__tests__/env.spec.ts b/playground/env/__tests__/env.spec.ts similarity index 97% rename from packages/playground/env/__tests__/env.spec.ts rename to playground/env/__tests__/env.spec.ts index 907cebc8037ce9..373e051a22a66e 100644 --- a/packages/playground/env/__tests__/env.spec.ts +++ b/playground/env/__tests__/env.spec.ts @@ -1,4 +1,4 @@ -import { isBuild } from 'testUtils' +import { isBuild, page } from '~utils' const mode = isBuild ? `production` : `development` diff --git a/packages/playground/env/index.html b/playground/env/index.html similarity index 100% rename from packages/playground/env/index.html rename to playground/env/index.html diff --git a/packages/playground/env/package.json b/playground/env/package.json similarity index 81% rename from packages/playground/env/package.json rename to playground/env/package.json index a97b5150530267..271cbf0a7d20c0 100644 --- a/packages/playground/env/package.json +++ b/playground/env/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "cross-env VITE_INLINE=inline-serve vite", "build": "cross-env VITE_INLINE=inline-build vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "devDependencies": { diff --git a/packages/playground/env/vite.config.js b/playground/env/vite.config.js similarity index 100% rename from packages/playground/env/vite.config.js rename to playground/env/vite.config.js diff --git a/packages/playground/extensions/__tests__/extensions.spec.ts b/playground/extensions/__tests__/extensions.spec.ts similarity index 84% rename from packages/playground/extensions/__tests__/extensions.spec.ts rename to playground/extensions/__tests__/extensions.spec.ts index 718cb40e790537..eb497a280e711a 100644 --- a/packages/playground/extensions/__tests__/extensions.spec.ts +++ b/playground/extensions/__tests__/extensions.spec.ts @@ -1,3 +1,5 @@ +import { browserLogs, page } from '~utils' + test('should have no 404s', () => { browserLogs.forEach((msg) => { expect(msg).not.toMatch('404') diff --git a/packages/playground/extensions/index.html b/playground/extensions/index.html similarity index 100% rename from packages/playground/extensions/index.html rename to playground/extensions/index.html diff --git a/packages/playground/extensions/package.json b/playground/extensions/package.json similarity index 69% rename from packages/playground/extensions/package.json rename to playground/extensions/package.json index d09b7da4d5300b..c653486edf6be6 100644 --- a/packages/playground/extensions/package.json +++ b/playground/extensions/package.json @@ -5,10 +5,10 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { - "vue": "^3.2.25" + "vue": "^3.2.33" } } diff --git a/packages/playground/extensions/vite.config.js b/playground/extensions/vite.config.js similarity index 100% rename from packages/playground/extensions/vite.config.js rename to playground/extensions/vite.config.js diff --git a/packages/playground/file-delete-restore/App.jsx b/playground/file-delete-restore/App.jsx similarity index 100% rename from packages/playground/file-delete-restore/App.jsx rename to playground/file-delete-restore/App.jsx diff --git a/packages/playground/file-delete-restore/Child.jsx b/playground/file-delete-restore/Child.jsx similarity index 100% rename from packages/playground/file-delete-restore/Child.jsx rename to playground/file-delete-restore/Child.jsx diff --git a/packages/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts b/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts similarity index 79% rename from packages/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts rename to playground/file-delete-restore/__tests__/file-delete-restore.spec.ts index 24f1237efedeec..a54f4b8da8e77e 100644 --- a/packages/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts +++ b/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts @@ -1,13 +1,15 @@ import { + addFile, editFile, - untilUpdated, + isBuild, + page, removeFile, - addFile, - isBuild -} from '../../testUtils' + untilUpdated +} from '~utils' -if (!isBuild) { - test('should hmr when file is deleted and restored', async () => { +test.runIf(isBuild)( + 'should hmr when file is deleted and restored', + async () => { await untilUpdated(() => page.textContent('p'), 'Child state 1') editFile('Child.jsx', (code) => @@ -39,7 +41,7 @@ if (!isBuild) { (code) => `import { useState } from 'react' import Child from './Child' - + function App() { return (
@@ -47,15 +49,11 @@ if (!isBuild) {
) } - + export default App ` ) await untilUpdated(() => page.textContent('p'), 'Child state 1') - }) -} else { - test('dummy test to make jest happy', async () => { - // Your test suite must contain at least one test. - }) -} + } +) diff --git a/packages/playground/file-delete-restore/index.html b/playground/file-delete-restore/index.html similarity index 100% rename from packages/playground/file-delete-restore/index.html rename to playground/file-delete-restore/index.html diff --git a/packages/playground/file-delete-restore/package.json b/playground/file-delete-restore/package.json similarity index 83% rename from packages/playground/file-delete-restore/package.json rename to playground/file-delete-restore/package.json index 8f9caa3578f8bd..b9c511aacfa62e 100644 --- a/packages/playground/file-delete-restore/package.json +++ b/playground/file-delete-restore/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { diff --git a/packages/playground/file-delete-restore/vite.config.js b/playground/file-delete-restore/vite.config.js similarity index 100% rename from packages/playground/file-delete-restore/vite.config.js rename to playground/file-delete-restore/vite.config.js diff --git a/playground/fs-serve/__tests__/fs-serve.spec.ts b/playground/fs-serve/__tests__/fs-serve.spec.ts new file mode 100644 index 00000000000000..6a21a35404ebb7 --- /dev/null +++ b/playground/fs-serve/__tests__/fs-serve.spec.ts @@ -0,0 +1,66 @@ +import { isServe, page, viteTestUrl } from '~utils' + +const json = require('../safe.json') +const stringified = JSON.stringify(json) + +describe.runIf(isServe)('main', () => { + beforeAll(async () => { + await page.goto(viteTestUrl + '/src/') + }) + + test('default import', async () => { + expect(await page.textContent('.full')).toBe(stringified) + }) + + test('named import', async () => { + expect(await page.textContent('.named')).toBe(json.msg) + }) + + test('safe fetch', async () => { + expect(await page.textContent('.safe-fetch')).toMatch('KEY=safe') + expect(await page.textContent('.safe-fetch-status')).toBe('200') + }) + + test('safe fetch with special characters', async () => { + expect( + await page.textContent('.safe-fetch-subdir-special-characters') + ).toMatch('KEY=safe') + expect( + await page.textContent('.safe-fetch-subdir-special-characters-status') + ).toBe('200') + }) + + test('unsafe fetch', async () => { + expect(await page.textContent('.unsafe-fetch')).toMatch('403 Restricted') + expect(await page.textContent('.unsafe-fetch-status')).toBe('403') + }) + + test('safe fs fetch', async () => { + expect(await page.textContent('.safe-fs-fetch')).toBe(stringified) + expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') + }) + + test('safe fs fetch with special characters', async () => { + expect(await page.textContent('.safe-fs-fetch-special-characters')).toBe( + stringified + ) + expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') + }) + + test('unsafe fs fetch', async () => { + expect(await page.textContent('.unsafe-fs-fetch')).toBe('') + expect(await page.textContent('.unsafe-fs-fetch-status')).toBe('403') + }) + + test('nested entry', async () => { + expect(await page.textContent('.nested-entry')).toBe('foobar') + }) + + test('nested entry', async () => { + expect(await page.textContent('.nested-entry')).toBe('foobar') + }) + + test('denied', async () => { + expect(await page.textContent('.unsafe-dotenv')).toBe('404') + }) +}) diff --git a/packages/playground/fs-serve/entry.js b/playground/fs-serve/entry.js similarity index 100% rename from packages/playground/fs-serve/entry.js rename to playground/fs-serve/entry.js diff --git a/packages/playground/fs-serve/nested/foo.js b/playground/fs-serve/nested/foo.js similarity index 100% rename from packages/playground/fs-serve/nested/foo.js rename to playground/fs-serve/nested/foo.js diff --git a/packages/playground/fs-serve/package.json b/playground/fs-serve/package.json similarity index 73% rename from packages/playground/fs-serve/package.json rename to playground/fs-serve/package.json index 45497d2a3c5e8a..c50be06a8cb286 100644 --- a/packages/playground/fs-serve/package.json +++ b/playground/fs-serve/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite root", "build": "vite build root", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/fs-serve/root/src/.env b/playground/fs-serve/root/src/.env similarity index 100% rename from packages/playground/fs-serve/root/src/.env rename to playground/fs-serve/root/src/.env diff --git a/packages/playground/fs-serve/root/src/index.html b/playground/fs-serve/root/src/index.html similarity index 100% rename from packages/playground/fs-serve/root/src/index.html rename to playground/fs-serve/root/src/index.html diff --git a/packages/playground/fs-serve/root/src/safe.txt b/playground/fs-serve/root/src/safe.txt similarity index 100% rename from packages/playground/fs-serve/root/src/safe.txt rename to playground/fs-serve/root/src/safe.txt diff --git "a/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" "b/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" similarity index 100% rename from "packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" rename to "playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" diff --git "a/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" "b/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" similarity index 100% rename from "packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" rename to "playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" diff --git a/packages/playground/fs-serve/root/src/subdir/safe.txt b/playground/fs-serve/root/src/subdir/safe.txt similarity index 100% rename from packages/playground/fs-serve/root/src/subdir/safe.txt rename to playground/fs-serve/root/src/subdir/safe.txt diff --git a/packages/playground/fs-serve/root/unsafe.txt b/playground/fs-serve/root/unsafe.txt similarity index 100% rename from packages/playground/fs-serve/root/unsafe.txt rename to playground/fs-serve/root/unsafe.txt diff --git a/packages/playground/fs-serve/root/vite.config.js b/playground/fs-serve/root/vite.config.js similarity index 100% rename from packages/playground/fs-serve/root/vite.config.js rename to playground/fs-serve/root/vite.config.js diff --git a/packages/playground/fs-serve/safe.json b/playground/fs-serve/safe.json similarity index 100% rename from packages/playground/fs-serve/safe.json rename to playground/fs-serve/safe.json diff --git a/packages/playground/fs-serve/unsafe.json b/playground/fs-serve/unsafe.json similarity index 100% rename from packages/playground/fs-serve/unsafe.json rename to playground/fs-serve/unsafe.json diff --git a/packages/playground/glob-import/__tests__/glob-import.spec.ts b/playground/glob-import/__tests__/glob-import.spec.ts similarity index 86% rename from packages/playground/glob-import/__tests__/glob-import.spec.ts rename to playground/glob-import/__tests__/glob-import.spec.ts index ebdf6c0ab29193..70f7ec252280a9 100644 --- a/packages/playground/glob-import/__tests__/glob-import.spec.ts +++ b/playground/glob-import/__tests__/glob-import.spec.ts @@ -2,9 +2,10 @@ import { addFile, editFile, isBuild, + page, removeFile, untilUpdated -} from '../../testUtils' +} from '~utils' const filteredResult = { './alias.js': { @@ -31,6 +32,12 @@ const json = isBuild msg: 'baz' } +const globWithAlias = { + '/dir/alias.js': { + default: 'hi' + } +} + const allResult = { // JSON file should be properly transformed '/dir/alias.js': { @@ -40,14 +47,15 @@ const allResult = { '/dir/foo.js': { msg: 'foo' }, - '/dir/index.js': { - globWithAlias: { - './alias.js': { - default: 'hi' + '/dir/index.js': isBuild + ? { + modules: filteredResult, + globWithAlias } - }, - modules: filteredResult - }, + : { + globWithAlias, + modules: filteredResult + }, '/dir/nested/bar.js': { modules: { '../baz.json': json @@ -67,7 +75,7 @@ const rawResult = { } const relativeRawResult = { - '../glob-import/dir/baz.json': { + './dir/baz.json': { msg: 'baz' } } @@ -93,6 +101,12 @@ test('import relative glob raw', async () => { ) }) +test('unassigned import processes', async () => { + expect(await page.textContent('.side-effect-result')).toBe( + 'Hello from side effect' + ) +}) + if (!isBuild) { test('hmr for adding/removing files', async () => { addFile('dir/a.js', '') diff --git a/packages/playground/glob-import/dir/alias.js b/playground/glob-import/dir/alias.js similarity index 100% rename from packages/playground/glob-import/dir/alias.js rename to playground/glob-import/dir/alias.js diff --git a/packages/playground/glob-import/dir/baz.json b/playground/glob-import/dir/baz.json similarity index 100% rename from packages/playground/glob-import/dir/baz.json rename to playground/glob-import/dir/baz.json diff --git a/packages/playground/glob-import/dir/foo.js b/playground/glob-import/dir/foo.js similarity index 100% rename from packages/playground/glob-import/dir/foo.js rename to playground/glob-import/dir/foo.js diff --git a/playground/glob-import/dir/index.js b/playground/glob-import/dir/index.js new file mode 100644 index 00000000000000..ab298abed485b3 --- /dev/null +++ b/playground/glob-import/dir/index.js @@ -0,0 +1,4 @@ +const modules = import.meta.glob('./*.(js|ts)', { eager: true }) +const globWithAlias = import.meta.glob('@dir/al*.js', { eager: true }) + +export { modules, globWithAlias } diff --git a/playground/glob-import/dir/nested/bar.js b/playground/glob-import/dir/nested/bar.js new file mode 100644 index 00000000000000..bb23a5a141de8e --- /dev/null +++ b/playground/glob-import/dir/nested/bar.js @@ -0,0 +1,4 @@ +const modules = import.meta.glob('../*.json', { eager: true }) + +export const msg = 'bar' +export { modules } diff --git a/packages/playground/glob-import/dir/node_modules/hoge.js b/playground/glob-import/dir/node_modules/hoge.js similarity index 100% rename from packages/playground/glob-import/dir/node_modules/hoge.js rename to playground/glob-import/dir/node_modules/hoge.js diff --git a/packages/playground/glob-import/index.html b/playground/glob-import/index.html similarity index 75% rename from packages/playground/glob-import/index.html rename to playground/glob-import/index.html index 64f456aeb4d6a2..6cff2aa0965c59 100644 --- a/packages/playground/glob-import/index.html +++ b/playground/glob-import/index.html @@ -2,6 +2,7 @@

 

 

+

 
 
 
 
 
 
 
+
+
diff --git a/packages/playground/glob-import/package.json b/playground/glob-import/package.json
similarity index 72%
rename from packages/playground/glob-import/package.json
rename to playground/glob-import/package.json
index 32abb932424757..2dd90e31b73b25 100644
--- a/packages/playground/glob-import/package.json
+++ b/playground/glob-import/package.json
@@ -5,7 +5,7 @@
   "scripts": {
     "dev": "vite",
     "build": "vite build",
-    "debug": "node --inspect-brk ../../vite/bin/vite",
+    "debug": "node --inspect-brk ../../packages/vite/bin/vite",
     "preview": "vite preview"
   }
 }
diff --git a/playground/glob-import/side-effect/writedom.js b/playground/glob-import/side-effect/writedom.js
new file mode 100644
index 00000000000000..e2ab04ba7f5cbe
--- /dev/null
+++ b/playground/glob-import/side-effect/writedom.js
@@ -0,0 +1,4 @@
+/* global document */
+document &&
+  (document.querySelector('.side-effect-result').textContent =
+    'Hello from side effect')
diff --git a/packages/playground/glob-import/vite.config.ts b/playground/glob-import/vite.config.ts
similarity index 100%
rename from packages/playground/glob-import/vite.config.ts
rename to playground/glob-import/vite.config.ts
diff --git a/packages/playground/hmr/__tests__/hmr.spec.ts b/playground/hmr/__tests__/hmr.spec.ts
similarity index 93%
rename from packages/playground/hmr/__tests__/hmr.spec.ts
rename to playground/hmr/__tests__/hmr.spec.ts
index 40b2bdf31b7956..d06fee31f110ea 100644
--- a/packages/playground/hmr/__tests__/hmr.spec.ts
+++ b/playground/hmr/__tests__/hmr.spec.ts
@@ -1,4 +1,12 @@
-import { isBuild, editFile, untilUpdated } from '../../testUtils'
+import {
+  browserLogs,
+  editFile,
+  getBg,
+  isBuild,
+  page,
+  untilUpdated,
+  viteTestUrl
+} from '~utils'
 
 test('should render', async () => {
   expect(await page.textContent('.app')).toBe('1')
@@ -195,6 +203,16 @@ if (!isBuild) {
     expect(await btn.textContent()).toBe('Counter 1')
   })
 
+  test('css in html hmr', async () => {
+    await page.goto(viteTestUrl)
+    expect(await getBg('.import-image')).toMatch('icon')
+    await page.goto(viteTestUrl + '/foo/')
+    expect(await getBg('.import-image')).toMatch('icon')
+    editFile('index.html', (code) => code.replace('url("./icon.png")', ''))
+    await page.waitForNavigation()
+    expect(await getBg('.import-image')).toMatch('')
+  })
+
   test('HTML', async () => {
     await page.goto(viteTestUrl + '/counter/index.html')
     let btn = await page.$('button')
diff --git a/packages/playground/hmr/counter/dep.ts b/playground/hmr/counter/dep.ts
similarity index 100%
rename from packages/playground/hmr/counter/dep.ts
rename to playground/hmr/counter/dep.ts
diff --git a/packages/playground/hmr/counter/index.html b/playground/hmr/counter/index.html
similarity index 100%
rename from packages/playground/hmr/counter/index.html
rename to playground/hmr/counter/index.html
diff --git a/packages/playground/hmr/counter/index.ts b/playground/hmr/counter/index.ts
similarity index 100%
rename from packages/playground/hmr/counter/index.ts
rename to playground/hmr/counter/index.ts
diff --git a/packages/playground/hmr/customFile.js b/playground/hmr/customFile.js
similarity index 100%
rename from packages/playground/hmr/customFile.js
rename to playground/hmr/customFile.js
diff --git a/packages/playground/hmr/event.d.ts b/playground/hmr/event.d.ts
similarity index 100%
rename from packages/playground/hmr/event.d.ts
rename to playground/hmr/event.d.ts
diff --git a/packages/playground/hmr/global.css b/playground/hmr/global.css
similarity index 100%
rename from packages/playground/hmr/global.css
rename to playground/hmr/global.css
diff --git a/packages/playground/hmr/hmr.ts b/playground/hmr/hmr.ts
similarity index 100%
rename from packages/playground/hmr/hmr.ts
rename to playground/hmr/hmr.ts
diff --git a/packages/playground/hmr/hmrDep.js b/playground/hmr/hmrDep.js
similarity index 100%
rename from packages/playground/hmr/hmrDep.js
rename to playground/hmr/hmrDep.js
diff --git a/packages/playground/hmr/hmrNestedDep.js b/playground/hmr/hmrNestedDep.js
similarity index 100%
rename from packages/playground/hmr/hmrNestedDep.js
rename to playground/hmr/hmrNestedDep.js
diff --git a/packages/playground/vue/public/icon.png b/playground/hmr/icon.png
similarity index 100%
rename from packages/playground/vue/public/icon.png
rename to playground/hmr/icon.png
diff --git a/packages/playground/hmr/index.html b/playground/hmr/index.html
similarity index 64%
rename from packages/playground/hmr/index.html
rename to playground/hmr/index.html
index 0add7c26011a01..65a2ed381b027a 100644
--- a/packages/playground/hmr/index.html
+++ b/playground/hmr/index.html
@@ -1,5 +1,13 @@
 
 
+
 
 
@@ -8,3 +16,4 @@
+
diff --git a/packages/playground/hmr/package.json b/playground/hmr/package.json similarity index 71% rename from packages/playground/hmr/package.json rename to playground/hmr/package.json index fa3654bdbdca85..b797d181b17ece 100644 --- a/packages/playground/hmr/package.json +++ b/playground/hmr/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/hmr/tsconfig.json b/playground/hmr/tsconfig.json similarity index 67% rename from packages/playground/hmr/tsconfig.json rename to playground/hmr/tsconfig.json index 41b16fdc65ec8c..e920e674091b5e 100644 --- a/packages/playground/hmr/tsconfig.json +++ b/playground/hmr/tsconfig.json @@ -1,6 +1,7 @@ { + "extends": "../tsconfig.json", "include": ["."], - "exclude": ["**/dist/**"], + "exclude": ["**/dist/**", "**/__tests__/**"], "compilerOptions": { "target": "es2019", "module": "esnext", @@ -10,6 +11,6 @@ "moduleResolution": "node", "baseUrl": ".", "jsx": "preserve", - "types": ["vite/client", "jest", "node"] + "types": ["vite/client", "node"] } } diff --git "a/packages/playground/hmr/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" "b/playground/hmr/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" similarity index 100% rename from "packages/playground/hmr/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" rename to "playground/hmr/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" diff --git a/packages/playground/hmr/vite.config.ts b/playground/hmr/vite.config.ts similarity index 100% rename from packages/playground/hmr/vite.config.ts rename to playground/hmr/vite.config.ts diff --git a/packages/playground/html/__tests__/html.spec.ts b/playground/html/__tests__/html.spec.ts similarity index 80% rename from packages/playground/html/__tests__/html.spec.ts rename to playground/html/__tests__/html.spec.ts index 834db1f6126cad..44372b324d5771 100644 --- a/packages/playground/html/__tests__/html.spec.ts +++ b/playground/html/__tests__/html.spec.ts @@ -1,4 +1,5 @@ -import { getColor, isBuild, editFile } from '../../testUtils' +import { beforeAll, describe, expect, test } from 'vitest' +import { editFile, getColor, isBuild, isServe, page, viteTestUrl } from '~utils' function testPage(isNested: boolean) { test('pre transform', async () => { @@ -79,7 +80,6 @@ describe('main', () => { describe('nested', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/nested/') }) @@ -88,17 +88,15 @@ describe('nested', () => { describe('nested w/ query', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/nested/index.html?v=1') }) testPage(true) }) -if (isBuild) { +describe.runIf(isBuild)('build', () => { describe('scriptAsync', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/scriptAsync.html') }) @@ -110,7 +108,6 @@ if (isBuild) { describe('scriptMixed', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/scriptMixed.html') }) @@ -124,7 +121,6 @@ if (isBuild) { // Ensure that the modulePreload polyfill is discarded in this case beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/zeroJS.html') }) @@ -164,11 +160,10 @@ if (isBuild) { ) }) }) -} +}) describe('noHead', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/noHead.html') }) @@ -183,7 +178,6 @@ describe('noHead', () => { describe('noBody', () => { beforeAll(async () => { - // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts await page.goto(viteTestUrl + '/noBody.html') }) @@ -211,28 +205,26 @@ describe('unicode path', () => { }) }) -if (!isBuild) { - describe('invalid', () => { - test('should be 500 with overlay', async () => { - const response = await page.goto(viteTestUrl + '/invalid.html') - expect(response.status()).toBe(500) +describe.runIf(isServe)('invalid', () => { + test('should be 500 with overlay', async () => { + const response = await page.goto(viteTestUrl + '/invalid.html') + expect(response.status()).toBe(500) - const errorOverlay = await page.waitForSelector('vite-error-overlay') - expect(errorOverlay).toBeTruthy() + const errorOverlay = await page.waitForSelector('vite-error-overlay') + expect(errorOverlay).toBeTruthy() - const message = await errorOverlay.$$eval('.message-body', (m) => { - return m[0].innerHTML - }) - expect(message).toMatch(/^Unable to parse HTML/) + const message = await errorOverlay.$$eval('.message-body', (m) => { + return m[0].innerHTML }) + expect(message).toMatch(/^Unable to parse HTML/) + }) - test('should reload when fixed', async () => { - const response = await page.goto(viteTestUrl + '/invalid.html') - await editFile('invalid.html', (content) => { - return content.replace('
Good') - }) - const content = await page.waitForSelector('text=Good HTML') - expect(content).toBeTruthy() + test('should reload when fixed', async () => { + await page.goto(viteTestUrl + '/invalid.html') + await editFile('invalid.html', (content) => { + return content.replace('
Good') }) + const content = await page.waitForSelector('text=Good HTML') + expect(content).toBeTruthy() }) -} +}) diff --git a/packages/playground/html/common.css b/playground/html/common.css similarity index 100% rename from packages/playground/html/common.css rename to playground/html/common.css diff --git a/packages/playground/html/emptyAttr.html b/playground/html/emptyAttr.html similarity index 100% rename from packages/playground/html/emptyAttr.html rename to playground/html/emptyAttr.html diff --git a/packages/playground/html/foo.html b/playground/html/foo.html similarity index 100% rename from packages/playground/html/foo.html rename to playground/html/foo.html diff --git a/packages/playground/html/index.html b/playground/html/index.html similarity index 50% rename from packages/playground/html/index.html rename to playground/html/index.html index 7320ff2b097db0..783cad93172f7a 100644 --- a/packages/playground/html/index.html +++ b/playground/html/index.html @@ -5,3 +5,6 @@

Hello

+ + + diff --git a/packages/playground/html/inline/common.js b/playground/html/inline/common.js similarity index 100% rename from packages/playground/html/inline/common.js rename to playground/html/inline/common.js diff --git a/packages/playground/html/inline/dep1.js b/playground/html/inline/dep1.js similarity index 100% rename from packages/playground/html/inline/dep1.js rename to playground/html/inline/dep1.js diff --git a/packages/playground/html/inline/dep2.js b/playground/html/inline/dep2.js similarity index 100% rename from packages/playground/html/inline/dep2.js rename to playground/html/inline/dep2.js diff --git a/packages/playground/html/inline/dep3.js b/playground/html/inline/dep3.js similarity index 100% rename from packages/playground/html/inline/dep3.js rename to playground/html/inline/dep3.js diff --git a/packages/playground/html/inline/module-graph.dot b/playground/html/inline/module-graph.dot similarity index 100% rename from packages/playground/html/inline/module-graph.dot rename to playground/html/inline/module-graph.dot diff --git a/packages/playground/html/inline/shared-1.html b/playground/html/inline/shared-1.html similarity index 100% rename from packages/playground/html/inline/shared-1.html rename to playground/html/inline/shared-1.html diff --git a/packages/playground/html/inline/shared-2.html b/playground/html/inline/shared-2.html similarity index 100% rename from packages/playground/html/inline/shared-2.html rename to playground/html/inline/shared-2.html diff --git a/packages/playground/html/inline/shared.js b/playground/html/inline/shared.js similarity index 100% rename from packages/playground/html/inline/shared.js rename to playground/html/inline/shared.js diff --git a/playground/html/inline/shared_a.html b/playground/html/inline/shared_a.html new file mode 100644 index 00000000000000..31fbd8fcc34bdf --- /dev/null +++ b/playground/html/inline/shared_a.html @@ -0,0 +1 @@ +

inline a

diff --git a/packages/playground/html/inline/unique.html b/playground/html/inline/unique.html similarity index 100% rename from packages/playground/html/inline/unique.html rename to playground/html/inline/unique.html diff --git a/packages/playground/html/inline/unique.js b/playground/html/inline/unique.js similarity index 100% rename from packages/playground/html/inline/unique.js rename to playground/html/inline/unique.js diff --git a/packages/playground/html/invalid.html b/playground/html/invalid.html similarity index 100% rename from packages/playground/html/invalid.html rename to playground/html/invalid.html diff --git a/packages/playground/html/link.html b/playground/html/link.html similarity index 100% rename from packages/playground/html/link.html rename to playground/html/link.html diff --git a/packages/playground/html/main.css b/playground/html/main.css similarity index 100% rename from packages/playground/html/main.css rename to playground/html/main.css diff --git a/packages/playground/html/main.js b/playground/html/main.js similarity index 100% rename from packages/playground/html/main.js rename to playground/html/main.js diff --git a/packages/playground/html/nested/index.html b/playground/html/nested/index.html similarity index 100% rename from packages/playground/html/nested/index.html rename to playground/html/nested/index.html diff --git a/packages/playground/html/nested/nested.css b/playground/html/nested/nested.css similarity index 100% rename from packages/playground/html/nested/nested.css rename to playground/html/nested/nested.css diff --git a/packages/playground/html/nested/nested.js b/playground/html/nested/nested.js similarity index 100% rename from packages/playground/html/nested/nested.js rename to playground/html/nested/nested.js diff --git a/packages/playground/html/noBody.html b/playground/html/noBody.html similarity index 100% rename from packages/playground/html/noBody.html rename to playground/html/noBody.html diff --git a/packages/playground/html/noHead.html b/playground/html/noHead.html similarity index 100% rename from packages/playground/html/noHead.html rename to playground/html/noHead.html diff --git a/packages/playground/html/package.json b/playground/html/package.json similarity index 71% rename from packages/playground/html/package.json rename to playground/html/package.json index a101033f8d3470..6db0bd91981ce0 100644 --- a/packages/playground/html/package.json +++ b/playground/html/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/html/scriptAsync.html b/playground/html/scriptAsync.html similarity index 100% rename from packages/playground/html/scriptAsync.html rename to playground/html/scriptAsync.html diff --git a/packages/playground/html/scriptMixed.html b/playground/html/scriptMixed.html similarity index 100% rename from packages/playground/html/scriptMixed.html rename to playground/html/scriptMixed.html diff --git a/packages/playground/html/shared.js b/playground/html/shared.js similarity index 100% rename from packages/playground/html/shared.js rename to playground/html/shared.js diff --git "a/packages/playground/html/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" "b/playground/html/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" similarity index 100% rename from "packages/playground/html/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" rename to "playground/html/unicode-path/\344\270\255\346\226\207-\343\201\253\343\201\273\343\202\223\343\201\224-\355\225\234\352\270\200-\360\237\214\225\360\237\214\226\360\237\214\227/index.html" diff --git a/packages/playground/html/vite.config.js b/playground/html/vite.config.js similarity index 98% rename from packages/playground/html/vite.config.js rename to playground/html/vite.config.js index 1703e02cc05366..bfe48675cbc18f 100644 --- a/packages/playground/html/vite.config.js +++ b/playground/html/vite.config.js @@ -17,6 +17,7 @@ module.exports = { zeroJS: resolve(__dirname, 'zeroJS.html'), noHead: resolve(__dirname, 'noHead.html'), noBody: resolve(__dirname, 'noBody.html'), + inlinea: resolve(__dirname, 'inline/shared_a.html'), inline1: resolve(__dirname, 'inline/shared-1.html'), inline2: resolve(__dirname, 'inline/shared-2.html'), inline3: resolve(__dirname, 'inline/unique.html'), diff --git a/packages/playground/html/zeroJS.html b/playground/html/zeroJS.html similarity index 100% rename from packages/playground/html/zeroJS.html rename to playground/html/zeroJS.html diff --git a/playground/js-sourcemap/__tests__/build.spec.ts b/playground/js-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..b30284731a76d9 --- /dev/null +++ b/playground/js-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,7 @@ +import { isBuild, serverLogs } from '~utils' + +test.runIf(isBuild)('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) +}) diff --git a/packages/playground/js-sourcemap/__tests__/serve.spec.ts b/playground/js-sourcemap/__tests__/serve.spec.ts similarity index 91% rename from packages/playground/js-sourcemap/__tests__/serve.spec.ts rename to playground/js-sourcemap/__tests__/serve.spec.ts index a1ffdddc37ecd5..8f36f5f6f832f1 100644 --- a/packages/playground/js-sourcemap/__tests__/serve.spec.ts +++ b/playground/js-sourcemap/__tests__/serve.spec.ts @@ -2,8 +2,10 @@ import { URL } from 'url' import { extractSourcemap, formatSourcemapForSnapshot, - isBuild -} from 'testUtils' + isBuild, + page, + serverLogs +} from '~utils' if (!isBuild) { test('js', async () => { @@ -18,12 +20,12 @@ if (!isBuild) { const js = await res.text() const map = extractSourcemap(js) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAO,aAAM,MAAM;", - "sources": Array [ + "sources": [ "/root/bar.ts", ], - "sourcesContent": Array [ + "sourcesContent": [ "export const bar = 'bar' ", ], diff --git a/packages/playground/js-sourcemap/bar.ts b/playground/js-sourcemap/bar.ts similarity index 100% rename from packages/playground/js-sourcemap/bar.ts rename to playground/js-sourcemap/bar.ts diff --git a/packages/playground/js-sourcemap/foo.js b/playground/js-sourcemap/foo.js similarity index 100% rename from packages/playground/js-sourcemap/foo.js rename to playground/js-sourcemap/foo.js diff --git a/packages/playground/js-sourcemap/index.html b/playground/js-sourcemap/index.html similarity index 100% rename from packages/playground/js-sourcemap/index.html rename to playground/js-sourcemap/index.html diff --git a/packages/playground/js-sourcemap/package.json b/playground/js-sourcemap/package.json similarity index 72% rename from packages/playground/js-sourcemap/package.json rename to playground/js-sourcemap/package.json index e5a97aea80830f..92b166d2f302c2 100644 --- a/packages/playground/js-sourcemap/package.json +++ b/playground/js-sourcemap/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/js-sourcemap/vite.config.js b/playground/js-sourcemap/vite.config.js similarity index 100% rename from packages/playground/js-sourcemap/vite.config.js rename to playground/js-sourcemap/vite.config.js diff --git a/packages/playground/json/__tests__/json.spec.ts b/playground/json/__tests__/json.spec.ts similarity index 96% rename from packages/playground/json/__tests__/json.spec.ts rename to playground/json/__tests__/json.spec.ts index 2897ee22332e44..8c64d619361bfb 100644 --- a/packages/playground/json/__tests__/json.spec.ts +++ b/playground/json/__tests__/json.spec.ts @@ -1,7 +1,7 @@ -import { isBuild } from '../../testUtils' +import { isBuild, page } from '~utils' -const json = require('../test.json') const deepJson = require('vue/package.json') +const json = require('../test.json') const stringified = JSON.stringify(json) const deepStringified = JSON.stringify(deepJson) diff --git a/packages/playground/json/index.html b/playground/json/index.html similarity index 100% rename from packages/playground/json/index.html rename to playground/json/index.html diff --git a/packages/playground/json/json-module/index.json b/playground/json/json-module/index.json similarity index 100% rename from packages/playground/json/json-module/index.json rename to playground/json/json-module/index.json diff --git a/packages/playground/json/json-module/package.json b/playground/json/json-module/package.json similarity index 100% rename from packages/playground/json/json-module/package.json rename to playground/json/json-module/package.json diff --git a/playground/json/package.json b/playground/json/package.json new file mode 100644 index 00000000000000..b919c42eb6ef5d --- /dev/null +++ b/playground/json/package.json @@ -0,0 +1,20 @@ +{ + "name": "test-json", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", + "preview": "vite preview", + "dev:ssr": "node server", + "serve:ssr": "cross-env NODE_ENV=production node server", + "debug:ssr": "node --inspect-brk server" + }, + "devDependencies": { + "cross-env": "^7.0.3", + "express": "^4.17.1", + "json-module": "file:./json-module", + "vue": "^3.2.33" + } +} diff --git a/packages/playground/json/public/public.json b/playground/json/public/public.json similarity index 100% rename from packages/playground/json/public/public.json rename to playground/json/public/public.json diff --git a/packages/playground/json/test.json b/playground/json/test.json similarity index 100% rename from packages/playground/json/test.json rename to playground/json/test.json diff --git a/packages/playground/legacy/__tests__/legacy.spec.ts b/playground/legacy/__tests__/legacy.spec.ts similarity index 82% rename from packages/playground/legacy/__tests__/legacy.spec.ts rename to playground/legacy/__tests__/legacy.spec.ts index 65bd39ff32b1d1..b21f42afcbd7ed 100644 --- a/packages/playground/legacy/__tests__/legacy.spec.ts +++ b/playground/legacy/__tests__/legacy.spec.ts @@ -1,11 +1,12 @@ import { - listAssets, findAssetFile, + getColor, isBuild, + listAssets, + page, readManifest, - untilUpdated, - getColor -} from '../../testUtils' + untilUpdated +} from '~utils' test('should work', async () => { expect(await page.textContent('#app')).toMatch('Hello') @@ -56,12 +57,23 @@ test('correctly emits styles', async () => { expect(await getColor('#app')).toBe('red') }) -if (isBuild) { +// dynamic import css +test('should load dynamic import with css', async () => { + await page.click('#dynamic-css-button') + await untilUpdated( + () => + page.$eval('#dynamic-css', (node) => window.getComputedStyle(node).color), + 'rgb(255, 0, 0)', + true + ) +}) + +describe.runIf(isBuild)('build', () => { test('should generate correct manifest', async () => { const manifest = readManifest() - expect(manifest['../../../vite/legacy-polyfills']).toBeDefined() - expect(manifest['../../../vite/legacy-polyfills'].src).toBe( - '../../../vite/legacy-polyfills' + expect(manifest['../../vite/legacy-polyfills']).toBeDefined() + expect(manifest['../../vite/legacy-polyfills'].src).toBe( + '../../vite/legacy-polyfills' ) }) @@ -87,4 +99,4 @@ if (isBuild) { test('includes structuredClone polyfill which is supported after core-js v3', () => { expect(findAssetFile(/polyfills-legacy/)).toMatch('"structuredClone"') }) -} +}) diff --git a/packages/playground/legacy/__tests__/ssr/legacy-ssr.spec.ts b/playground/legacy/__tests__/ssr/legacy-ssr.spec.ts similarity index 65% rename from packages/playground/legacy/__tests__/ssr/legacy-ssr.spec.ts rename to playground/legacy/__tests__/ssr/legacy-ssr.spec.ts index dad9b94d83509e..b5cfe82cd93910 100644 --- a/packages/playground/legacy/__tests__/ssr/legacy-ssr.spec.ts +++ b/playground/legacy/__tests__/ssr/legacy-ssr.spec.ts @@ -1,9 +1,9 @@ -import { isBuild } from '../../../testUtils' import { port } from './serve' +import { isBuild, page } from '~utils' const url = `http://localhost:${port}` -if (isBuild) { +describe.runIf(isBuild)('legacy-ssr', () => { test('should work', async () => { await page.goto(url) expect(await page.textContent('#app')).toMatch('Hello') @@ -13,8 +13,4 @@ if (isBuild) { // SSR build is always modern expect(await page.textContent('#env')).toMatch('false') }) -} else { - // this test doesn't support serve mode - // must contain at least one test - test('should work', () => void 0) -} +}) diff --git a/packages/playground/legacy/__tests__/ssr/serve.js b/playground/legacy/__tests__/ssr/serve.ts similarity index 72% rename from packages/playground/legacy/__tests__/ssr/serve.js rename to playground/legacy/__tests__/ssr/serve.ts index c7ef2ed3520e53..ec16b39e550965 100644 --- a/packages/playground/legacy/__tests__/ssr/serve.js +++ b/playground/legacy/__tests__/ssr/serve.ts @@ -1,16 +1,11 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace +// this is automatically detected by playground/vitestSetup.ts and will replace // the default e2e test serve behavior -const path = require('path') -const { ports } = require('../../../testUtils') +import path from 'path' +import { ports } from '~utils' -const port = (exports.port = ports['legacy/ssr']) +export const port = ports['legacy/ssr'] -/** - * @param {string} root - * @param {boolean} _isProd - */ -exports.serve = async function serve(root, _isProd) { +export async function serve(root: string, _isProd: boolean) { const { build } = require('vite') await build({ root, diff --git a/packages/playground/legacy/async.js b/playground/legacy/async.js similarity index 100% rename from packages/playground/legacy/async.js rename to playground/legacy/async.js diff --git a/playground/legacy/dynamic.css b/playground/legacy/dynamic.css new file mode 100644 index 00000000000000..160ee45a8a850a --- /dev/null +++ b/playground/legacy/dynamic.css @@ -0,0 +1,3 @@ +#dynamic-css { + color: red; +} diff --git a/packages/playground/legacy/entry-server.js b/playground/legacy/entry-server.js similarity index 100% rename from packages/playground/legacy/entry-server.js rename to playground/legacy/entry-server.js diff --git a/packages/playground/legacy/immutable-chunk.js b/playground/legacy/immutable-chunk.js similarity index 100% rename from packages/playground/legacy/immutable-chunk.js rename to playground/legacy/immutable-chunk.js diff --git a/packages/playground/legacy/index.html b/playground/legacy/index.html similarity index 72% rename from packages/playground/legacy/index.html rename to playground/legacy/index.html index d481766463cd4f..cbf6242fad756b 100644 --- a/packages/playground/legacy/index.html +++ b/playground/legacy/index.html @@ -4,4 +4,6 @@

+ +
diff --git a/packages/playground/legacy/main.js b/playground/legacy/main.js similarity index 84% rename from packages/playground/legacy/main.js rename to playground/legacy/main.js index 31579b4717810d..157b6c8448e9c3 100644 --- a/packages/playground/legacy/main.js +++ b/playground/legacy/main.js @@ -42,6 +42,14 @@ import('./immutable-chunk.js') text('#assets', assets.join('\n')) }) +// dynamic css +document + .querySelector('#dynamic-css-button') + .addEventListener('click', async () => { + await import('./dynamic.css') + text('#dynamic-css', 'dynamic import css') + }) + function text(el, text) { document.querySelector(el).textContent = text } diff --git a/packages/playground/legacy/package.json b/playground/legacy/package.json similarity index 65% rename from packages/playground/legacy/package.json rename to playground/legacy/package.json index 3a3315c42aa832..4f11c234573f40 100644 --- a/packages/playground/legacy/package.json +++ b/playground/legacy/package.json @@ -6,11 +6,12 @@ "dev": "vite", "build": "vite build --debug legacy", "build:custom-filename": "vite --config ./vite.config-custom-filename.js build --debug legacy", - "debug": "node --inspect-brk ../../vite/bin/vite", + "build:dynamic-css": "vite --config ./vite.config-dynamic-css.js build --debug legacy", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "devDependencies": { "@vitejs/plugin-legacy": "workspace:*", - "express": "^4.17.1" + "express": "^4.18.1" } } diff --git a/packages/playground/legacy/style.css b/playground/legacy/style.css similarity index 100% rename from packages/playground/legacy/style.css rename to playground/legacy/style.css diff --git a/packages/playground/legacy/vite.config-custom-filename.js b/playground/legacy/vite.config-custom-filename.js similarity index 100% rename from packages/playground/legacy/vite.config-custom-filename.js rename to playground/legacy/vite.config-custom-filename.js diff --git a/playground/legacy/vite.config-dynamic-css.js b/playground/legacy/vite.config-dynamic-css.js new file mode 100644 index 00000000000000..10565768ac4d49 --- /dev/null +++ b/playground/legacy/vite.config-dynamic-css.js @@ -0,0 +1,39 @@ +const fs = require('fs') +const path = require('path') +const legacy = require('@vitejs/plugin-legacy').default + +module.exports = { + plugins: [ + legacy({ + targets: 'IE 11' + }) + ], + + build: { + cssCodeSplit: true, + manifest: true, + rollupOptions: { + output: { + chunkFileNames(chunkInfo) { + if (chunkInfo.name === 'immutable-chunk') { + return `assets/${chunkInfo.name}.js` + } + + return `assets/chunk-[name].[hash].js` + } + } + } + }, + + // special test only hook + // for tests, remove ` diff --git a/packages/playground/lib/index.html b/playground/lib/index.html similarity index 100% rename from packages/playground/lib/index.html rename to playground/lib/index.html diff --git a/packages/playground/lib/package.json b/playground/lib/package.json similarity index 72% rename from packages/playground/lib/package.json rename to playground/lib/package.json index 2c3ae4be3d4bcb..66b827b7c84179 100644 --- a/packages/playground/lib/package.json +++ b/playground/lib/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/playground/lib/src/dynamic.css b/playground/lib/src/dynamic.css new file mode 100644 index 00000000000000..4378c8d328cfbe --- /dev/null +++ b/playground/lib/src/dynamic.css @@ -0,0 +1,4 @@ +@import 'https://cdn.jsdelivr.net/npm/@mdi/font@5.9.55/css/materialdesignicons.min.css'; +.dynamic { + color: red; +} diff --git a/playground/lib/src/index.css b/playground/lib/src/index.css new file mode 100644 index 00000000000000..b0bd670bd9ecad --- /dev/null +++ b/playground/lib/src/index.css @@ -0,0 +1,3 @@ +.index { + color: blue; +} diff --git a/playground/lib/src/main.js b/playground/lib/src/main.js new file mode 100644 index 00000000000000..cb2fb3b842dc4f --- /dev/null +++ b/playground/lib/src/main.js @@ -0,0 +1,6 @@ +export default function myLib(sel) { + // Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951) + console.log({ ...'foo' }) + + document.querySelector(sel).textContent = 'It works' +} diff --git a/packages/playground/lib/src/main2.js b/playground/lib/src/main2.js similarity index 73% rename from packages/playground/lib/src/main2.js rename to playground/lib/src/main2.js index 0c729fad8d165c..f19a16bb128949 100644 --- a/packages/playground/lib/src/main2.js +++ b/playground/lib/src/main2.js @@ -1,4 +1,9 @@ +import './index.css' + export default async function message(sel) { const message = await import('./message.js') + + await import('./dynamic.css') + document.querySelector(sel).textContent = message.default } diff --git a/packages/playground/lib/src/message.js b/playground/lib/src/message.js similarity index 100% rename from packages/playground/lib/src/message.js rename to playground/lib/src/message.js diff --git a/packages/playground/lib/vite.config.js b/playground/lib/vite.config.js similarity index 89% rename from packages/playground/lib/vite.config.js rename to playground/lib/vite.config.js index 50cd188b1a40cc..72c040d38d6dcf 100644 --- a/packages/playground/lib/vite.config.js +++ b/playground/lib/vite.config.js @@ -10,7 +10,7 @@ module.exports = { entry: path.resolve(__dirname, 'src/main.js'), name: 'MyLib', formats: ['es', 'umd', 'iife'], - fileName: (format) => `my-lib-custom-filename.${format}.js` + fileName: 'my-lib-custom-filename' } }, plugins: [ diff --git a/packages/playground/lib/vite.dyimport.config.js b/playground/lib/vite.dyimport.config.js similarity index 94% rename from packages/playground/lib/vite.dyimport.config.js rename to playground/lib/vite.dyimport.config.js index 76311f4b8ba138..d738503f0c9d09 100644 --- a/packages/playground/lib/vite.dyimport.config.js +++ b/playground/lib/vite.dyimport.config.js @@ -6,7 +6,6 @@ const path = require('path') */ module.exports = { build: { - minify: false, lib: { entry: path.resolve(__dirname, 'src/main2.js'), formats: ['es'], diff --git a/packages/playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts b/playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts similarity index 84% rename from packages/playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts rename to playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts index 56c0b46c8a3e6f..e61c2187556f08 100644 --- a/packages/playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts +++ b/playground/multiple-entrypoints/__tests__/multiple-entrypoints.spec.ts @@ -1,4 +1,4 @@ -import { getColor, untilUpdated } from '../../testUtils' +import { getColor, page, untilUpdated } from '~utils' test('should have css applied on second dynamic import', async () => { await untilUpdated(() => page.textContent('.content'), 'Initial', true) diff --git a/packages/playground/multiple-entrypoints/deps.json b/playground/multiple-entrypoints/deps.json similarity index 100% rename from packages/playground/multiple-entrypoints/deps.json rename to playground/multiple-entrypoints/deps.json diff --git a/packages/playground/multiple-entrypoints/dynamic-a.js b/playground/multiple-entrypoints/dynamic-a.js similarity index 100% rename from packages/playground/multiple-entrypoints/dynamic-a.js rename to playground/multiple-entrypoints/dynamic-a.js diff --git a/packages/playground/multiple-entrypoints/dynamic-b.js b/playground/multiple-entrypoints/dynamic-b.js similarity index 100% rename from packages/playground/multiple-entrypoints/dynamic-b.js rename to playground/multiple-entrypoints/dynamic-b.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a0.js b/playground/multiple-entrypoints/entrypoints/a0.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a0.js rename to playground/multiple-entrypoints/entrypoints/a0.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a1.js b/playground/multiple-entrypoints/entrypoints/a1.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a1.js rename to playground/multiple-entrypoints/entrypoints/a1.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a10.js b/playground/multiple-entrypoints/entrypoints/a10.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a10.js rename to playground/multiple-entrypoints/entrypoints/a10.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a11.js b/playground/multiple-entrypoints/entrypoints/a11.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a11.js rename to playground/multiple-entrypoints/entrypoints/a11.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a12.js b/playground/multiple-entrypoints/entrypoints/a12.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a12.js rename to playground/multiple-entrypoints/entrypoints/a12.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a13.js b/playground/multiple-entrypoints/entrypoints/a13.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a13.js rename to playground/multiple-entrypoints/entrypoints/a13.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a14.js b/playground/multiple-entrypoints/entrypoints/a14.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a14.js rename to playground/multiple-entrypoints/entrypoints/a14.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a15.js b/playground/multiple-entrypoints/entrypoints/a15.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a15.js rename to playground/multiple-entrypoints/entrypoints/a15.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a16.js b/playground/multiple-entrypoints/entrypoints/a16.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a16.js rename to playground/multiple-entrypoints/entrypoints/a16.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a17.js b/playground/multiple-entrypoints/entrypoints/a17.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a17.js rename to playground/multiple-entrypoints/entrypoints/a17.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a18.js b/playground/multiple-entrypoints/entrypoints/a18.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a18.js rename to playground/multiple-entrypoints/entrypoints/a18.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a19.js b/playground/multiple-entrypoints/entrypoints/a19.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a19.js rename to playground/multiple-entrypoints/entrypoints/a19.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a2.js b/playground/multiple-entrypoints/entrypoints/a2.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a2.js rename to playground/multiple-entrypoints/entrypoints/a2.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a20.js b/playground/multiple-entrypoints/entrypoints/a20.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a20.js rename to playground/multiple-entrypoints/entrypoints/a20.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a21.js b/playground/multiple-entrypoints/entrypoints/a21.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a21.js rename to playground/multiple-entrypoints/entrypoints/a21.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a22.js b/playground/multiple-entrypoints/entrypoints/a22.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a22.js rename to playground/multiple-entrypoints/entrypoints/a22.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a23.js b/playground/multiple-entrypoints/entrypoints/a23.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a23.js rename to playground/multiple-entrypoints/entrypoints/a23.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a24.js b/playground/multiple-entrypoints/entrypoints/a24.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a24.js rename to playground/multiple-entrypoints/entrypoints/a24.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a3.js b/playground/multiple-entrypoints/entrypoints/a3.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a3.js rename to playground/multiple-entrypoints/entrypoints/a3.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a4.js b/playground/multiple-entrypoints/entrypoints/a4.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a4.js rename to playground/multiple-entrypoints/entrypoints/a4.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a5.js b/playground/multiple-entrypoints/entrypoints/a5.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a5.js rename to playground/multiple-entrypoints/entrypoints/a5.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a6.js b/playground/multiple-entrypoints/entrypoints/a6.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a6.js rename to playground/multiple-entrypoints/entrypoints/a6.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a7.js b/playground/multiple-entrypoints/entrypoints/a7.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a7.js rename to playground/multiple-entrypoints/entrypoints/a7.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a8.js b/playground/multiple-entrypoints/entrypoints/a8.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a8.js rename to playground/multiple-entrypoints/entrypoints/a8.js diff --git a/packages/playground/multiple-entrypoints/entrypoints/a9.js b/playground/multiple-entrypoints/entrypoints/a9.js similarity index 100% rename from packages/playground/multiple-entrypoints/entrypoints/a9.js rename to playground/multiple-entrypoints/entrypoints/a9.js diff --git a/packages/playground/multiple-entrypoints/index.html b/playground/multiple-entrypoints/index.html similarity index 100% rename from packages/playground/multiple-entrypoints/index.html rename to playground/multiple-entrypoints/index.html diff --git a/packages/playground/multiple-entrypoints/index.js b/playground/multiple-entrypoints/index.js similarity index 100% rename from packages/playground/multiple-entrypoints/index.js rename to playground/multiple-entrypoints/index.js diff --git a/packages/playground/multiple-entrypoints/package.json b/playground/multiple-entrypoints/package.json similarity index 72% rename from packages/playground/multiple-entrypoints/package.json rename to playground/multiple-entrypoints/package.json index 6c338a64518ddb..07818337be7bba 100644 --- a/packages/playground/multiple-entrypoints/package.json +++ b/playground/multiple-entrypoints/package.json @@ -5,11 +5,11 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "devDependencies": { "fast-glob": "^3.2.11", - "sass": "^1.43.4" + "sass": "^1.51.0" } } diff --git a/packages/playground/multiple-entrypoints/reference.js b/playground/multiple-entrypoints/reference.js similarity index 100% rename from packages/playground/multiple-entrypoints/reference.js rename to playground/multiple-entrypoints/reference.js diff --git a/packages/playground/multiple-entrypoints/reference.scss b/playground/multiple-entrypoints/reference.scss similarity index 100% rename from packages/playground/multiple-entrypoints/reference.scss rename to playground/multiple-entrypoints/reference.scss diff --git a/packages/playground/multiple-entrypoints/vite.config.js b/playground/multiple-entrypoints/vite.config.js similarity index 100% rename from packages/playground/multiple-entrypoints/vite.config.js rename to playground/multiple-entrypoints/vite.config.js diff --git a/packages/playground/nested-deps/__tests__/nested-deps.spec.ts b/playground/nested-deps/__tests__/nested-deps.spec.ts similarity index 94% rename from packages/playground/nested-deps/__tests__/nested-deps.spec.ts rename to playground/nested-deps/__tests__/nested-deps.spec.ts index 2ef0e191da7b50..e4adb68792d116 100644 --- a/packages/playground/nested-deps/__tests__/nested-deps.spec.ts +++ b/playground/nested-deps/__tests__/nested-deps.spec.ts @@ -1,3 +1,5 @@ +import { page } from '~utils' + test('handle nested package', async () => { expect(await page.textContent('.a')).toBe('A@2.0.0') expect(await page.textContent('.b')).toBe('B@1.0.0') diff --git a/packages/playground/nested-deps/index.html b/playground/nested-deps/index.html similarity index 100% rename from packages/playground/nested-deps/index.html rename to playground/nested-deps/index.html diff --git a/packages/playground/nested-deps/package.json b/playground/nested-deps/package.json similarity index 87% rename from packages/playground/nested-deps/package.json rename to playground/nested-deps/package.json index d7450d0545fcb4..cbfcfe44df551b 100644 --- a/packages/playground/nested-deps/package.json +++ b/playground/nested-deps/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { diff --git a/packages/playground/nested-deps/test-package-a/index.js b/playground/nested-deps/test-package-a/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-a/index.js rename to playground/nested-deps/test-package-a/index.js diff --git a/packages/playground/nested-deps/test-package-a/package.json b/playground/nested-deps/test-package-a/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-a/package.json rename to playground/nested-deps/test-package-a/package.json diff --git a/packages/playground/nested-deps/test-package-b/index.js b/playground/nested-deps/test-package-b/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-b/index.js rename to playground/nested-deps/test-package-b/index.js diff --git a/packages/playground/nested-deps/test-package-b/node_modules/test-package-a/index.js b/playground/nested-deps/test-package-b/node_modules/test-package-a/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-b/node_modules/test-package-a/index.js rename to playground/nested-deps/test-package-b/node_modules/test-package-a/index.js diff --git a/packages/playground/nested-deps/test-package-b/node_modules/test-package-a/package.json b/playground/nested-deps/test-package-b/node_modules/test-package-a/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-b/node_modules/test-package-a/package.json rename to playground/nested-deps/test-package-b/node_modules/test-package-a/package.json diff --git a/packages/playground/nested-deps/test-package-b/package.json b/playground/nested-deps/test-package-b/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-b/package.json rename to playground/nested-deps/test-package-b/package.json diff --git a/packages/playground/nested-deps/test-package-c/index-es.js b/playground/nested-deps/test-package-c/index-es.js similarity index 100% rename from packages/playground/nested-deps/test-package-c/index-es.js rename to playground/nested-deps/test-package-c/index-es.js diff --git a/packages/playground/nested-deps/test-package-c/index.js b/playground/nested-deps/test-package-c/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-c/index.js rename to playground/nested-deps/test-package-c/index.js diff --git a/packages/playground/nested-deps/test-package-c/package.json b/playground/nested-deps/test-package-c/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-c/package.json rename to playground/nested-deps/test-package-c/package.json diff --git a/packages/playground/nested-deps/test-package-c/side.js b/playground/nested-deps/test-package-c/side.js similarity index 100% rename from packages/playground/nested-deps/test-package-c/side.js rename to playground/nested-deps/test-package-c/side.js diff --git a/packages/playground/nested-deps/test-package-d/index.js b/playground/nested-deps/test-package-d/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-d/index.js rename to playground/nested-deps/test-package-d/index.js diff --git a/packages/playground/nested-deps/test-package-d/package.json b/playground/nested-deps/test-package-d/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-d/package.json rename to playground/nested-deps/test-package-d/package.json diff --git a/packages/playground/nested-deps/test-package-d/test-package-d-nested/index.js b/playground/nested-deps/test-package-d/test-package-d-nested/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-d/test-package-d-nested/index.js rename to playground/nested-deps/test-package-d/test-package-d-nested/index.js diff --git a/packages/playground/nested-deps/test-package-d/test-package-d-nested/package.json b/playground/nested-deps/test-package-d/test-package-d-nested/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-d/test-package-d-nested/package.json rename to playground/nested-deps/test-package-d/test-package-d-nested/package.json diff --git a/packages/playground/nested-deps/test-package-e/index.js b/playground/nested-deps/test-package-e/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-e/index.js rename to playground/nested-deps/test-package-e/index.js diff --git a/packages/playground/nested-deps/test-package-e/package.json b/playground/nested-deps/test-package-e/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-e/package.json rename to playground/nested-deps/test-package-e/package.json diff --git a/packages/playground/nested-deps/test-package-e/test-package-e-excluded/index.js b/playground/nested-deps/test-package-e/test-package-e-excluded/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-e/test-package-e-excluded/index.js rename to playground/nested-deps/test-package-e/test-package-e-excluded/index.js diff --git a/packages/playground/nested-deps/test-package-e/test-package-e-excluded/package.json b/playground/nested-deps/test-package-e/test-package-e-excluded/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-e/test-package-e-excluded/package.json rename to playground/nested-deps/test-package-e/test-package-e-excluded/package.json diff --git a/packages/playground/nested-deps/test-package-e/test-package-e-included/index.js b/playground/nested-deps/test-package-e/test-package-e-included/index.js similarity index 100% rename from packages/playground/nested-deps/test-package-e/test-package-e-included/index.js rename to playground/nested-deps/test-package-e/test-package-e-included/index.js diff --git a/packages/playground/nested-deps/test-package-e/test-package-e-included/package.json b/playground/nested-deps/test-package-e/test-package-e-included/package.json similarity index 100% rename from packages/playground/nested-deps/test-package-e/test-package-e-included/package.json rename to playground/nested-deps/test-package-e/test-package-e-included/package.json diff --git a/packages/playground/nested-deps/vite.config.js b/playground/nested-deps/vite.config.js similarity index 100% rename from packages/playground/nested-deps/vite.config.js rename to playground/nested-deps/vite.config.js diff --git a/playground/optimize-deps/.env b/playground/optimize-deps/.env new file mode 100644 index 00000000000000..995fca4af2ee24 --- /dev/null +++ b/playground/optimize-deps/.env @@ -0,0 +1 @@ +NODE_ENV=production \ No newline at end of file diff --git a/packages/playground/optimize-deps/.hidden-dir/foo.js b/playground/optimize-deps/.hidden-dir/foo.js similarity index 100% rename from packages/playground/optimize-deps/.hidden-dir/foo.js rename to playground/optimize-deps/.hidden-dir/foo.js diff --git a/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts b/playground/optimize-deps/__tests__/optimize-deps.spec.ts similarity index 95% rename from packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts rename to playground/optimize-deps/__tests__/optimize-deps.spec.ts index d95a6d984cd9aa..898d75f6bf9f0d 100644 --- a/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts +++ b/playground/optimize-deps/__tests__/optimize-deps.spec.ts @@ -1,4 +1,4 @@ -import { getColor, isBuild } from '../../testUtils' +import { getColor, isBuild, page } from '~utils' test('default + named imports from cjs dep (react)', async () => { expect(await page.textContent('.cjs button')).toBe('count is 0') @@ -62,6 +62,10 @@ test('import * from optimized dep', async () => { expect(await page.textContent('.import-star')).toMatch(`[success]`) }) +test('import from dep with process.env.NODE_ENV', async () => { + expect(await page.textContent('.node-env')).toMatch(`prod`) +}) + test('import from dep with .notjs files', async () => { expect(await page.textContent('.not-js')).toMatch(`[success]`) }) diff --git a/packages/playground/optimize-deps/cjs-dynamic.js b/playground/optimize-deps/cjs-dynamic.js similarity index 100% rename from packages/playground/optimize-deps/cjs-dynamic.js rename to playground/optimize-deps/cjs-dynamic.js diff --git a/packages/playground/optimize-deps/cjs.js b/playground/optimize-deps/cjs.js similarity index 100% rename from packages/playground/optimize-deps/cjs.js rename to playground/optimize-deps/cjs.js diff --git a/packages/playground/optimize-deps/dedupe.js b/playground/optimize-deps/dedupe.js similarity index 100% rename from packages/playground/optimize-deps/dedupe.js rename to playground/optimize-deps/dedupe.js diff --git a/packages/playground/optimize-deps/dep-cjs-compiled-from-cjs/index.js b/playground/optimize-deps/dep-cjs-compiled-from-cjs/index.js similarity index 100% rename from packages/playground/optimize-deps/dep-cjs-compiled-from-cjs/index.js rename to playground/optimize-deps/dep-cjs-compiled-from-cjs/index.js diff --git a/packages/playground/optimize-deps/dep-cjs-compiled-from-cjs/package.json b/playground/optimize-deps/dep-cjs-compiled-from-cjs/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-cjs-compiled-from-cjs/package.json rename to playground/optimize-deps/dep-cjs-compiled-from-cjs/package.json diff --git a/packages/playground/optimize-deps/dep-cjs-compiled-from-esm/index.js b/playground/optimize-deps/dep-cjs-compiled-from-esm/index.js similarity index 100% rename from packages/playground/optimize-deps/dep-cjs-compiled-from-esm/index.js rename to playground/optimize-deps/dep-cjs-compiled-from-esm/index.js diff --git a/packages/playground/optimize-deps/dep-cjs-compiled-from-esm/package.json b/playground/optimize-deps/dep-cjs-compiled-from-esm/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-cjs-compiled-from-esm/package.json rename to playground/optimize-deps/dep-cjs-compiled-from-esm/package.json diff --git a/packages/playground/optimize-deps/dep-esbuild-plugin-transform/index.js b/playground/optimize-deps/dep-esbuild-plugin-transform/index.js similarity index 100% rename from packages/playground/optimize-deps/dep-esbuild-plugin-transform/index.js rename to playground/optimize-deps/dep-esbuild-plugin-transform/index.js diff --git a/packages/playground/optimize-deps/dep-esbuild-plugin-transform/package.json b/playground/optimize-deps/dep-esbuild-plugin-transform/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-esbuild-plugin-transform/package.json rename to playground/optimize-deps/dep-esbuild-plugin-transform/package.json diff --git a/packages/playground/optimize-deps/dep-linked-include/Test.vue b/playground/optimize-deps/dep-linked-include/Test.vue similarity index 100% rename from packages/playground/optimize-deps/dep-linked-include/Test.vue rename to playground/optimize-deps/dep-linked-include/Test.vue diff --git a/packages/playground/optimize-deps/dep-linked-include/foo.js b/playground/optimize-deps/dep-linked-include/foo.js similarity index 100% rename from packages/playground/optimize-deps/dep-linked-include/foo.js rename to playground/optimize-deps/dep-linked-include/foo.js diff --git a/packages/playground/optimize-deps/dep-linked-include/index.mjs b/playground/optimize-deps/dep-linked-include/index.mjs similarity index 100% rename from packages/playground/optimize-deps/dep-linked-include/index.mjs rename to playground/optimize-deps/dep-linked-include/index.mjs diff --git a/packages/playground/optimize-deps/dep-linked-include/package.json b/playground/optimize-deps/dep-linked-include/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-linked-include/package.json rename to playground/optimize-deps/dep-linked-include/package.json diff --git a/packages/playground/optimize-deps/dep-linked-include/test.css b/playground/optimize-deps/dep-linked-include/test.css similarity index 100% rename from packages/playground/optimize-deps/dep-linked-include/test.css rename to playground/optimize-deps/dep-linked-include/test.css diff --git a/packages/playground/optimize-deps/dep-linked/index.js b/playground/optimize-deps/dep-linked/index.js similarity index 100% rename from packages/playground/optimize-deps/dep-linked/index.js rename to playground/optimize-deps/dep-linked/index.js diff --git a/packages/playground/optimize-deps/dep-linked/package.json b/playground/optimize-deps/dep-linked/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-linked/package.json rename to playground/optimize-deps/dep-linked/package.json diff --git a/playground/optimize-deps/dep-node-env/index.js b/playground/optimize-deps/dep-node-env/index.js new file mode 100644 index 00000000000000..8548c37894539f --- /dev/null +++ b/playground/optimize-deps/dep-node-env/index.js @@ -0,0 +1 @@ +export const env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev' diff --git a/playground/optimize-deps/dep-node-env/package.json b/playground/optimize-deps/dep-node-env/package.json new file mode 100644 index 00000000000000..59a00fb153c522 --- /dev/null +++ b/playground/optimize-deps/dep-node-env/package.json @@ -0,0 +1,5 @@ +{ + "name": "dep-node-env", + "private": true, + "version": "1.0.0" +} diff --git a/packages/playground/optimize-deps/dep-not-js/foo.js b/playground/optimize-deps/dep-not-js/foo.js similarity index 100% rename from packages/playground/optimize-deps/dep-not-js/foo.js rename to playground/optimize-deps/dep-not-js/foo.js diff --git a/packages/playground/optimize-deps/dep-not-js/index.notjs b/playground/optimize-deps/dep-not-js/index.notjs similarity index 100% rename from packages/playground/optimize-deps/dep-not-js/index.notjs rename to playground/optimize-deps/dep-not-js/index.notjs diff --git a/packages/playground/optimize-deps/dep-not-js/package.json b/playground/optimize-deps/dep-not-js/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-not-js/package.json rename to playground/optimize-deps/dep-not-js/package.json diff --git a/packages/playground/optimize-deps/dep-with-dynamic-import/dynamic.js b/playground/optimize-deps/dep-with-dynamic-import/dynamic.js similarity index 100% rename from packages/playground/optimize-deps/dep-with-dynamic-import/dynamic.js rename to playground/optimize-deps/dep-with-dynamic-import/dynamic.js diff --git a/packages/playground/optimize-deps/dep-with-dynamic-import/index.js b/playground/optimize-deps/dep-with-dynamic-import/index.js similarity index 100% rename from packages/playground/optimize-deps/dep-with-dynamic-import/index.js rename to playground/optimize-deps/dep-with-dynamic-import/index.js diff --git a/packages/playground/optimize-deps/dep-with-dynamic-import/package.json b/playground/optimize-deps/dep-with-dynamic-import/package.json similarity index 100% rename from packages/playground/optimize-deps/dep-with-dynamic-import/package.json rename to playground/optimize-deps/dep-with-dynamic-import/package.json diff --git a/packages/playground/optimize-deps/glob/foo.js b/playground/optimize-deps/glob/foo.js similarity index 100% rename from packages/playground/optimize-deps/glob/foo.js rename to playground/optimize-deps/glob/foo.js diff --git a/packages/playground/optimize-deps/index.html b/playground/optimize-deps/index.html similarity index 94% rename from packages/playground/optimize-deps/index.html rename to playground/optimize-deps/index.html index 2be896d00acba9..d11383bfcb3e04 100644 --- a/packages/playground/optimize-deps/index.html +++ b/playground/optimize-deps/index.html @@ -38,6 +38,9 @@

Optimizing force included dep even when it's linked

import * as ...

+

Import from dependency with process.env.NODE_ENV

+
+

Import from dependency with .notjs files

@@ -73,7 +76,7 @@

Reused variable names

` +const DYNAMIC_STYLES = ` + +` + async function createServer( root = process.cwd(), isProd = process.env.NODE_ENV === 'production' @@ -42,15 +50,30 @@ async function createServer( // use vite's connect instance as middleware app.use(vite.middlewares) - app.use('*', async (req, res) => { + app.use('*', async (req, res, next) => { try { let [url] = req.originalUrl.split('?') if (url.endsWith('/')) url += 'index.html' + if (url.startsWith('/favicon.ico')) { + return res.status(404).end('404') + } + if (url.startsWith('/@id/__x00__')) { + return next() + } + const htmlLoc = resolve(`.${url}`) - let html = fs.readFileSync(htmlLoc, 'utf8') - html = html.replace('', `${DYNAMIC_SCRIPTS}`) - html = await vite.transformIndexHtml(url, html) + let template = fs.readFileSync(htmlLoc, 'utf-8') + + template = template.replace( + '', + `${DYNAMIC_SCRIPTS}${DYNAMIC_STYLES}` + ) + + // Force calling transformIndexHtml with url === '/', to simulate + // usage by ecosystem that was recommended in the SSR documentation + // as `const url = req.originalUrl` + const html = await vite.transformIndexHtml('/', template) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { diff --git a/packages/playground/ssr-html/src/app.js b/playground/ssr-html/src/app.js similarity index 100% rename from packages/playground/ssr-html/src/app.js rename to playground/ssr-html/src/app.js diff --git a/packages/playground/optimize-missing-deps/__test__/serve.js b/playground/ssr-pug/__tests__/serve.ts similarity index 63% rename from packages/playground/optimize-missing-deps/__test__/serve.js rename to playground/ssr-pug/__tests__/serve.ts index 89a6ce3593cd0e..b7b7ff0f8cd75f 100644 --- a/packages/playground/optimize-missing-deps/__test__/serve.js +++ b/playground/ssr-pug/__tests__/serve.ts @@ -1,17 +1,15 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace +// this is automatically detected by playground/vitestSetup.ts and will replace // the default e2e test serve behavior -const path = require('path') -const { ports } = require('../../testUtils') +import path from 'path' +import kill from 'kill-port' +import { ports } from '~utils' -const port = (exports.port = ports['optimize-missing-deps']) +export const port = ports['ssr-pug'] + +export async function serve(root, isProd) { + await kill(port) -/** - * @param {string} root - * @param {boolean} isProd - */ -exports.serve = async function serve(root, isProd) { const { createServer } = require(path.resolve(root, 'server.js')) const { app, vite } = await createServer(root, isProd) diff --git a/packages/playground/ssr-pug/__tests__/ssr-pug.spec.ts b/playground/ssr-pug/__tests__/ssr-pug.spec.ts similarity index 97% rename from packages/playground/ssr-pug/__tests__/ssr-pug.spec.ts rename to playground/ssr-pug/__tests__/ssr-pug.spec.ts index e34b8a91fc3421..bcf66c8f5ad128 100644 --- a/packages/playground/ssr-pug/__tests__/ssr-pug.spec.ts +++ b/playground/ssr-pug/__tests__/ssr-pug.spec.ts @@ -1,5 +1,6 @@ -import { port } from './serve' import fetch from 'node-fetch' +import { port } from './serve' +import { page } from '~utils' const url = `http://localhost:${port}` diff --git a/packages/playground/ssr-pug/index.pug b/playground/ssr-pug/index.pug similarity index 100% rename from packages/playground/ssr-pug/index.pug rename to playground/ssr-pug/index.pug diff --git a/packages/playground/ssr-pug/package.json b/playground/ssr-pug/package.json similarity index 91% rename from packages/playground/ssr-pug/package.json rename to playground/ssr-pug/package.json index e2282b20565c1b..afa80df44a18bc 100644 --- a/packages/playground/ssr-pug/package.json +++ b/playground/ssr-pug/package.json @@ -9,7 +9,7 @@ }, "devDependencies": { "cross-env": "^7.0.3", - "express": "^4.17.1", + "express": "^4.18.1", "pug": "^3.0.2" } } diff --git a/packages/playground/ssr-pug/server.js b/playground/ssr-pug/server.js similarity index 100% rename from packages/playground/ssr-pug/server.js rename to playground/ssr-pug/server.js diff --git a/packages/playground/ssr-pug/src/app.js b/playground/ssr-pug/src/app.js similarity index 100% rename from packages/playground/ssr-pug/src/app.js rename to playground/ssr-pug/src/app.js diff --git a/packages/playground/ssr-react/__tests__/serve.js b/playground/ssr-react/__tests__/serve.ts similarity index 73% rename from packages/playground/ssr-react/__tests__/serve.js rename to playground/ssr-react/__tests__/serve.ts index 07476e0726e268..b3cb38da7e5fc8 100644 --- a/packages/playground/ssr-react/__tests__/serve.js +++ b/playground/ssr-react/__tests__/serve.ts @@ -1,24 +1,20 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace +// this is automatically detected by playground/vitestSetup.ts and will replace // the default e2e test serve behavior -const path = require('path') -const { ports } = require('../../testUtils') +import path from 'path' +import kill from 'kill-port' +import { ports } from '~utils' -const port = (exports.port = ports['ssr-react']) +export const port = ports['ssr-react'] -/** - * @param {string} root - * @param {boolean} isProd - */ -exports.serve = async function serve(root, isProd) { +export async function serve(root: string, isProd: boolean) { if (isProd) { // build first const { build } = require('vite') // client build await build({ root, - logLevel: 'silent', // exceptions are logged by Jest + logLevel: 'silent', // exceptions are logged by Vitest build: { target: 'esnext', minify: false, @@ -38,6 +34,8 @@ exports.serve = async function serve(root, isProd) { }) } + await kill(port) + const { createServer } = require(path.resolve(root, 'server.js')) const { app, vite } = await createServer(root, isProd) diff --git a/packages/playground/ssr-react/__tests__/ssr-react.spec.ts b/playground/ssr-react/__tests__/ssr-react.spec.ts similarity index 92% rename from packages/playground/ssr-react/__tests__/ssr-react.spec.ts rename to playground/ssr-react/__tests__/ssr-react.spec.ts index 2235d4ae4d0edf..62bb7d2014f770 100644 --- a/packages/playground/ssr-react/__tests__/ssr-react.spec.ts +++ b/playground/ssr-react/__tests__/ssr-react.spec.ts @@ -1,6 +1,6 @@ -import { editFile, untilUpdated } from '../../testUtils' -import { port } from './serve' import fetch from 'node-fetch' +import { port } from './serve' +import { browserLogs, editFile, page, untilUpdated } from '~utils' const url = `http://localhost:${port}` @@ -56,7 +56,7 @@ test('client navigation', async () => { await untilUpdated(() => page.textContent('h1'), 'changed') }) -test(`circular dependecies modules doesn't throw`, async () => { +test(`circular dependencies modules doesn't throw`, async () => { await page.goto(url) expect(await page.textContent('.circ-dep-init')).toMatch( 'circ-dep-init-a circ-dep-init-b' diff --git a/packages/playground/ssr-react/index.html b/playground/ssr-react/index.html similarity index 100% rename from packages/playground/ssr-react/index.html rename to playground/ssr-react/index.html diff --git a/packages/playground/ssr-react/package.json b/playground/ssr-react/package.json similarity index 85% rename from packages/playground/ssr-react/package.json rename to playground/ssr-react/package.json index a05bcc08806f3b..e6a954b56c839c 100644 --- a/packages/playground/ssr-react/package.json +++ b/playground/ssr-react/package.json @@ -14,14 +14,14 @@ "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2", - "react-router": "^5.2.1", - "react-router-dom": "^5.3.0" + "react-router": "^5.3.1", + "react-router-dom": "^5.3.1" }, "devDependencies": { "@vitejs/plugin-react": "workspace:*", "compression": "^1.7.4", "cross-env": "^7.0.3", - "express": "^4.17.1", - "serve-static": "^1.14.1" + "express": "^4.18.1", + "serve-static": "^1.15.0" } } diff --git a/packages/playground/ssr-react/prerender.js b/playground/ssr-react/prerender.js similarity index 100% rename from packages/playground/ssr-react/prerender.js rename to playground/ssr-react/prerender.js diff --git a/packages/playground/ssr-react/server.js b/playground/ssr-react/server.js similarity index 99% rename from packages/playground/ssr-react/server.js rename to playground/ssr-react/server.js index 1876439c18fa88..bac272a95a2900 100644 --- a/packages/playground/ssr-react/server.js +++ b/playground/ssr-react/server.js @@ -60,6 +60,7 @@ async function createServer( render = (await vite.ssrLoadModule('/src/entry-server.jsx')).render } else { template = indexProd + // @ts-ignore render = require('./dist/server/entry-server.js').render } diff --git a/packages/playground/ssr-react/src/App.jsx b/playground/ssr-react/src/App.jsx similarity index 93% rename from packages/playground/ssr-react/src/App.jsx rename to playground/ssr-react/src/App.jsx index 1c598add666efb..59e14cd5c3eea0 100644 --- a/packages/playground/ssr-react/src/App.jsx +++ b/playground/ssr-react/src/App.jsx @@ -2,7 +2,7 @@ import { Link, Route, Switch } from 'react-router-dom' // Auto generates routes from files under ./pages // https://vitejs.dev/guide/features.html#glob-import -const pages = import.meta.globEager('./pages/*.jsx') +const pages = import.meta.glob('./pages/*.jsx', { eager: true }) const routes = Object.keys(pages).map((path) => { const name = path.match(/\.\/pages\/(.*)\.jsx$/)[1] diff --git a/packages/playground/ssr-react/src/add.js b/playground/ssr-react/src/add.js similarity index 100% rename from packages/playground/ssr-react/src/add.js rename to playground/ssr-react/src/add.js diff --git a/packages/playground/ssr-react/src/circular-dep-init/README.md b/playground/ssr-react/src/circular-dep-init/README.md similarity index 100% rename from packages/playground/ssr-react/src/circular-dep-init/README.md rename to playground/ssr-react/src/circular-dep-init/README.md diff --git a/packages/playground/ssr-react/src/circular-dep-init/circular-dep-init.js b/playground/ssr-react/src/circular-dep-init/circular-dep-init.js similarity index 100% rename from packages/playground/ssr-react/src/circular-dep-init/circular-dep-init.js rename to playground/ssr-react/src/circular-dep-init/circular-dep-init.js diff --git a/packages/playground/ssr-react/src/circular-dep-init/module-a.js b/playground/ssr-react/src/circular-dep-init/module-a.js similarity index 100% rename from packages/playground/ssr-react/src/circular-dep-init/module-a.js rename to playground/ssr-react/src/circular-dep-init/module-a.js diff --git a/packages/playground/ssr-react/src/circular-dep-init/module-b.js b/playground/ssr-react/src/circular-dep-init/module-b.js similarity index 100% rename from packages/playground/ssr-react/src/circular-dep-init/module-b.js rename to playground/ssr-react/src/circular-dep-init/module-b.js diff --git a/packages/playground/ssr-react/src/entry-client.jsx b/playground/ssr-react/src/entry-client.jsx similarity index 100% rename from packages/playground/ssr-react/src/entry-client.jsx rename to playground/ssr-react/src/entry-client.jsx diff --git a/packages/playground/ssr-react/src/entry-server.jsx b/playground/ssr-react/src/entry-server.jsx similarity index 100% rename from packages/playground/ssr-react/src/entry-server.jsx rename to playground/ssr-react/src/entry-server.jsx diff --git a/packages/playground/ssr-react/src/forked-deadlock/README.md b/playground/ssr-react/src/forked-deadlock/README.md similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/README.md rename to playground/ssr-react/src/forked-deadlock/README.md diff --git a/packages/playground/ssr-react/src/forked-deadlock/common-module.js b/playground/ssr-react/src/forked-deadlock/common-module.js similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/common-module.js rename to playground/ssr-react/src/forked-deadlock/common-module.js diff --git a/packages/playground/ssr-react/src/forked-deadlock/deadlock-fuse-module.js b/playground/ssr-react/src/forked-deadlock/deadlock-fuse-module.js similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/deadlock-fuse-module.js rename to playground/ssr-react/src/forked-deadlock/deadlock-fuse-module.js diff --git a/packages/playground/ssr-react/src/forked-deadlock/fuse-stuck-bridge-module.js b/playground/ssr-react/src/forked-deadlock/fuse-stuck-bridge-module.js similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/fuse-stuck-bridge-module.js rename to playground/ssr-react/src/forked-deadlock/fuse-stuck-bridge-module.js diff --git a/packages/playground/ssr-react/src/forked-deadlock/middle-module.js b/playground/ssr-react/src/forked-deadlock/middle-module.js similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/middle-module.js rename to playground/ssr-react/src/forked-deadlock/middle-module.js diff --git a/packages/playground/ssr-react/src/forked-deadlock/stuck-module.js b/playground/ssr-react/src/forked-deadlock/stuck-module.js similarity index 100% rename from packages/playground/ssr-react/src/forked-deadlock/stuck-module.js rename to playground/ssr-react/src/forked-deadlock/stuck-module.js diff --git a/packages/playground/ssr-react/src/multiply.js b/playground/ssr-react/src/multiply.js similarity index 100% rename from packages/playground/ssr-react/src/multiply.js rename to playground/ssr-react/src/multiply.js diff --git a/packages/playground/ssr-react/src/pages/About.jsx b/playground/ssr-react/src/pages/About.jsx similarity index 100% rename from packages/playground/ssr-react/src/pages/About.jsx rename to playground/ssr-react/src/pages/About.jsx diff --git a/packages/playground/ssr-react/src/pages/Env.jsx b/playground/ssr-react/src/pages/Env.jsx similarity index 100% rename from packages/playground/ssr-react/src/pages/Env.jsx rename to playground/ssr-react/src/pages/Env.jsx diff --git a/packages/playground/ssr-react/src/pages/Home.jsx b/playground/ssr-react/src/pages/Home.jsx similarity index 100% rename from packages/playground/ssr-react/src/pages/Home.jsx rename to playground/ssr-react/src/pages/Home.jsx diff --git a/packages/playground/ssr-react/vite.config.js b/playground/ssr-react/vite.config.js similarity index 100% rename from packages/playground/ssr-react/vite.config.js rename to playground/ssr-react/vite.config.js diff --git a/packages/playground/ssr-vue/__tests__/serve.js b/playground/ssr-vue/__tests__/serve.ts similarity index 73% rename from packages/playground/ssr-vue/__tests__/serve.js rename to playground/ssr-vue/__tests__/serve.ts index 5bcd5a4639877a..ae9accd412c01c 100644 --- a/packages/playground/ssr-vue/__tests__/serve.js +++ b/playground/ssr-vue/__tests__/serve.ts @@ -1,24 +1,20 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace +// this is automatically detected by playground/vitestSetup.ts and will replace // the default e2e test serve behavior -const path = require('path') -const { ports } = require('../../testUtils') +import path from 'path' +import kill from 'kill-port' +import { ports } from '~utils' -const port = (exports.port = ports['ssr-vue']) +export const port = ports['ssr-vue'] -/** - * @param {string} root - * @param {boolean} isProd - */ -exports.serve = async function serve(root, isProd) { +export async function serve(root, isProd) { if (isProd) { // build first const { build } = require('vite') // client build await build({ root, - logLevel: 'silent', // exceptions are logged by Jest + logLevel: 'silent', // exceptions are logged by Vitest build: { target: 'esnext', minify: false, @@ -38,6 +34,8 @@ exports.serve = async function serve(root, isProd) { }) } + await kill(port) + const { createServer } = require(path.resolve(root, 'server.js')) const { app, vite } = await createServer(root, isProd) diff --git a/packages/playground/ssr-vue/__tests__/ssr-vue.spec.ts b/playground/ssr-vue/__tests__/ssr-vue.spec.ts similarity index 86% rename from packages/playground/ssr-vue/__tests__/ssr-vue.spec.ts rename to playground/ssr-vue/__tests__/ssr-vue.spec.ts index 952e287a7f12aa..c58cea4cd13e59 100644 --- a/packages/playground/ssr-vue/__tests__/ssr-vue.spec.ts +++ b/playground/ssr-vue/__tests__/ssr-vue.spec.ts @@ -1,7 +1,14 @@ -import { editFile, getColor, isBuild, untilUpdated } from '../../testUtils' -import { port } from './serve' -import fetch from 'node-fetch' import { resolve } from 'path' +import fetch from 'node-fetch' +import { port } from './serve' +import { + browserLogs, + editFile, + getColor, + isBuild, + page, + untilUpdated +} from '~utils' const url = `http://localhost:${port}` @@ -110,6 +117,7 @@ test('css', async () => { } else { // During dev, the CSS is loaded from async chunk and we may have to wait // when the test runs concurrently. + await page.waitForLoadState('networkidle') await untilUpdated(() => getColor('h1'), 'green') await untilUpdated(() => getColor('.jsx'), 'blue') } @@ -141,11 +149,13 @@ test('nested virtual module', async () => { test('hydration', async () => { expect(await page.textContent('button')).toMatch('0') await page.click('button') + await page.waitForLoadState('networkidle') expect(await page.textContent('button')).toMatch('1') }) test('hmr', async () => { editFile('src/pages/Home.vue', (code) => code.replace('Home', 'changed')) + await page.waitForLoadState('networkidle') await untilUpdated(() => page.textContent('h1'), 'changed') }) @@ -154,6 +164,7 @@ test('client navigation', async () => { await page.click('a[href="/about"]') await untilUpdated(() => page.textContent('h1'), 'About') editFile('src/pages/About.vue', (code) => code.replace('About', 'changed')) + await page.waitForLoadState('networkidle') await untilUpdated(() => page.textContent('h1'), 'changed') await page.click('a[href="/"]') await untilUpdated(() => page.textContent('a[href="/"]'), 'Home') @@ -164,19 +175,17 @@ test('import.meta.url', async () => { expect(await page.textContent('.protocol')).toEqual('file:') }) -test('dynamic css file should be preloaded', async () => { - if (isBuild) { - await page.goto(url) - const homeHtml = await (await fetch(url)).text() - const re = /link rel="modulepreload".*?href="\/assets\/(Home\.\w{8}\.js)"/ - const filename = re.exec(homeHtml)[1] - const manifest = require(resolve( - process.cwd(), - './packages/temp/ssr-vue/dist/client/ssr-manifest.json' - )) - const depFile = manifest[filename] - for (const file of depFile) { - expect(homeHtml).toMatch(file) - } +test.runIf(isBuild)('dynamic css file should be preloaded', async () => { + await page.goto(url) + const homeHtml = await (await fetch(url)).text() + const re = /link rel="modulepreload".*?href="\/assets\/(Home\.\w{8}\.js)"/ + const filename = re.exec(homeHtml)[1] + const manifest = require(resolve( + process.cwd(), + './playground-temp/ssr-vue/dist/client/ssr-manifest.json' + )) + const depFile = manifest[filename] + for (const file of depFile) { + expect(homeHtml).toMatch(file) } }) diff --git a/packages/playground/ssr-vue/dep-import-type/deep/index.d.ts b/playground/ssr-vue/dep-import-type/deep/index.d.ts similarity index 100% rename from packages/playground/ssr-vue/dep-import-type/deep/index.d.ts rename to playground/ssr-vue/dep-import-type/deep/index.d.ts diff --git a/packages/playground/ssr-vue/dep-import-type/package.json b/playground/ssr-vue/dep-import-type/package.json similarity index 100% rename from packages/playground/ssr-vue/dep-import-type/package.json rename to playground/ssr-vue/dep-import-type/package.json diff --git a/packages/playground/ssr-vue/example-external-component/ExampleExternalComponent.vue b/playground/ssr-vue/example-external-component/ExampleExternalComponent.vue similarity index 100% rename from packages/playground/ssr-vue/example-external-component/ExampleExternalComponent.vue rename to playground/ssr-vue/example-external-component/ExampleExternalComponent.vue diff --git a/packages/playground/ssr-vue/example-external-component/index.js b/playground/ssr-vue/example-external-component/index.js similarity index 100% rename from packages/playground/ssr-vue/example-external-component/index.js rename to playground/ssr-vue/example-external-component/index.js diff --git a/packages/playground/ssr-vue/example-external-component/package.json b/playground/ssr-vue/example-external-component/package.json similarity index 100% rename from packages/playground/ssr-vue/example-external-component/package.json rename to playground/ssr-vue/example-external-component/package.json diff --git a/packages/playground/ssr-vue/index.html b/playground/ssr-vue/index.html similarity index 100% rename from packages/playground/ssr-vue/index.html rename to playground/ssr-vue/index.html diff --git a/packages/playground/ssr-vue/package.json b/playground/ssr-vue/package.json similarity index 90% rename from packages/playground/ssr-vue/package.json rename to playground/ssr-vue/package.json index 4a385336a97603..0464ebeeb76e05 100644 --- a/packages/playground/ssr-vue/package.json +++ b/playground/ssr-vue/package.json @@ -15,8 +15,8 @@ }, "dependencies": { "example-external-component": "file:example-external-component", - "vue": "^3.2.25", - "vue-router": "^4.0.0", + "vue": "^3.2.33", + "vue-router": "^4.0.15", "vuex": "^4.0.2" }, "devDependencies": { @@ -25,7 +25,7 @@ "compression": "^1.7.4", "cross-env": "^7.0.3", "dep-import-type": "link:./dep-import-type", - "express": "^4.17.1", - "serve-static": "^1.14.1" + "express": "^4.18.1", + "serve-static": "^1.15.0" } } diff --git a/packages/playground/ssr-vue/prerender.js b/playground/ssr-vue/prerender.js similarity index 100% rename from packages/playground/ssr-vue/prerender.js rename to playground/ssr-vue/prerender.js diff --git a/packages/playground/ssr-vue/server.js b/playground/ssr-vue/server.js similarity index 99% rename from packages/playground/ssr-vue/server.js rename to playground/ssr-vue/server.js index 642f274647294f..c98d2984f82e5c 100644 --- a/packages/playground/ssr-vue/server.js +++ b/playground/ssr-vue/server.js @@ -63,6 +63,7 @@ async function createServer( render = (await vite.ssrLoadModule('/src/entry-server.js')).render } else { template = indexProd + // @ts-ignore render = require('./dist/server/entry-server.js').render } diff --git a/packages/playground/ssr-vue/src/App.vue b/playground/ssr-vue/src/App.vue similarity index 91% rename from packages/playground/ssr-vue/src/App.vue rename to playground/ssr-vue/src/App.vue index dc8bfca16a59ab..d824089ef249e4 100644 --- a/packages/playground/ssr-vue/src/App.vue +++ b/playground/ssr-vue/src/App.vue @@ -4,7 +4,9 @@ About - +
+ +
diff --git a/packages/playground/ssr-vue/src/assets/button.css b/playground/ssr-vue/src/assets/button.css similarity index 100% rename from packages/playground/ssr-vue/src/assets/button.css rename to playground/ssr-vue/src/assets/button.css diff --git a/packages/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff b/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff similarity index 100% rename from packages/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff rename to playground/ssr-vue/src/assets/fonts/Inter-Italic.woff diff --git a/packages/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff2 b/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff2 similarity index 100% rename from packages/playground/ssr-vue/src/assets/fonts/Inter-Italic.woff2 rename to playground/ssr-vue/src/assets/fonts/Inter-Italic.woff2 diff --git a/packages/playground/ssr-vue/src/assets/logo.png b/playground/ssr-vue/src/assets/logo.png similarity index 100% rename from packages/playground/ssr-vue/src/assets/logo.png rename to playground/ssr-vue/src/assets/logo.png diff --git a/packages/playground/ssr-vue/src/components/Foo.jsx b/playground/ssr-vue/src/components/Foo.jsx similarity index 100% rename from packages/playground/ssr-vue/src/components/Foo.jsx rename to playground/ssr-vue/src/components/Foo.jsx diff --git a/packages/playground/ssr-vue/src/components/ImportType.vue b/playground/ssr-vue/src/components/ImportType.vue similarity index 100% rename from packages/playground/ssr-vue/src/components/ImportType.vue rename to playground/ssr-vue/src/components/ImportType.vue diff --git a/packages/playground/ssr-vue/src/components/button.js b/playground/ssr-vue/src/components/button.js similarity index 100% rename from packages/playground/ssr-vue/src/components/button.js rename to playground/ssr-vue/src/components/button.js diff --git a/packages/playground/ssr-vue/src/components/foo.css b/playground/ssr-vue/src/components/foo.css similarity index 100% rename from packages/playground/ssr-vue/src/components/foo.css rename to playground/ssr-vue/src/components/foo.css diff --git a/packages/playground/ssr-vue/src/entry-client.js b/playground/ssr-vue/src/entry-client.js similarity index 100% rename from packages/playground/ssr-vue/src/entry-client.js rename to playground/ssr-vue/src/entry-client.js diff --git a/packages/playground/ssr-vue/src/entry-server.js b/playground/ssr-vue/src/entry-server.js similarity index 100% rename from packages/playground/ssr-vue/src/entry-server.js rename to playground/ssr-vue/src/entry-server.js diff --git a/packages/playground/ssr-vue/src/main.js b/playground/ssr-vue/src/main.js similarity index 100% rename from packages/playground/ssr-vue/src/main.js rename to playground/ssr-vue/src/main.js diff --git a/packages/playground/ssr-vue/src/pages/About.vue b/playground/ssr-vue/src/pages/About.vue similarity index 86% rename from packages/playground/ssr-vue/src/pages/About.vue rename to playground/ssr-vue/src/pages/About.vue index 2c8589f7ff109a..ea6510808fd943 100644 --- a/packages/playground/ssr-vue/src/pages/About.vue +++ b/playground/ssr-vue/src/pages/About.vue @@ -11,7 +11,7 @@ export default { async setup() { const url = import.meta.env.SSR ? import.meta.url - : document.querySelector('.import-meta-url').textContent + : document.querySelector('.import-meta-url')?.textContent return { msg: 'About', url diff --git a/packages/playground/ssr-vue/src/pages/External.vue b/playground/ssr-vue/src/pages/External.vue similarity index 100% rename from packages/playground/ssr-vue/src/pages/External.vue rename to playground/ssr-vue/src/pages/External.vue diff --git a/packages/playground/ssr-vue/src/pages/Home.vue b/playground/ssr-vue/src/pages/Home.vue similarity index 91% rename from packages/playground/ssr-vue/src/pages/Home.vue rename to playground/ssr-vue/src/pages/Home.vue index 32a33882cc2324..7f595e7437e600 100644 --- a/packages/playground/ssr-vue/src/pages/Home.vue +++ b/playground/ssr-vue/src/pages/Home.vue @@ -33,8 +33,8 @@ function load(file) { } const url = import.meta.env.SSR ? import.meta.url - : document.querySelector('.import-meta-url').textContent -const protocol = new URL(url).protocol + : document.querySelector('.import-meta-url')?.textContent +const protocol = url ? new URL(url).protocol : undefined const state = reactive({ count: 0, diff --git a/packages/playground/ssr-vue/src/pages/Store.vue b/playground/ssr-vue/src/pages/Store.vue similarity index 100% rename from packages/playground/ssr-vue/src/pages/Store.vue rename to playground/ssr-vue/src/pages/Store.vue diff --git a/packages/playground/ssr-vue/src/router.js b/playground/ssr-vue/src/router.js similarity index 100% rename from packages/playground/ssr-vue/src/router.js rename to playground/ssr-vue/src/router.js diff --git a/packages/playground/ssr-vue/vite.config.js b/playground/ssr-vue/vite.config.js similarity index 100% rename from packages/playground/ssr-vue/vite.config.js rename to playground/ssr-vue/vite.config.js diff --git a/packages/playground/ssr-vue/vite.config.noexternal.js b/playground/ssr-vue/vite.config.noexternal.js similarity index 100% rename from packages/playground/ssr-vue/vite.config.noexternal.js rename to playground/ssr-vue/vite.config.noexternal.js diff --git a/packages/playground/ssr-webworker/__tests__/serve.js b/playground/ssr-webworker/__tests__/serve.ts similarity index 72% rename from packages/playground/ssr-webworker/__tests__/serve.js rename to playground/ssr-webworker/__tests__/serve.ts index 38a957b0a333ea..5094a7df54e1ec 100644 --- a/packages/playground/ssr-webworker/__tests__/serve.js +++ b/playground/ssr-webworker/__tests__/serve.ts @@ -1,17 +1,15 @@ -// @ts-check -// this is automtically detected by scripts/jestPerTestSetup.ts and will replace +// this is automatically detected by playground/vitestSetup.ts and will replace // the default e2e test serve behavior -const path = require('path') -const { ports } = require('../../testUtils') +import path from 'path' +import kill from 'kill-port' +import { ports } from '~utils' -const port = (exports.port = ports['ssr-webworker']) +export const port = ports['ssr-webworker'] + +export async function serve(root: string, isProd: boolean) { + await kill(port) -/** - * @param {string} root - * @param {boolean} isProd - */ -exports.serve = async function serve(root, isProd) { // we build first, regardless of whether it's prod/build mode // because Vite doesn't support the concept of a "webworker server" const { build } = require('vite') diff --git a/packages/playground/ssr-webworker/__tests__/ssr-webworker.spec.ts b/playground/ssr-webworker/__tests__/ssr-webworker.spec.ts similarity index 91% rename from packages/playground/ssr-webworker/__tests__/ssr-webworker.spec.ts rename to playground/ssr-webworker/__tests__/ssr-webworker.spec.ts index 30d2bb93e495b1..7a5c1bdad2880e 100644 --- a/packages/playground/ssr-webworker/__tests__/ssr-webworker.spec.ts +++ b/playground/ssr-webworker/__tests__/ssr-webworker.spec.ts @@ -1,4 +1,5 @@ import { port } from './serve' +import { page } from '~utils' const url = `http://localhost:${port}` diff --git a/packages/playground/ssr-webworker/package.json b/playground/ssr-webworker/package.json similarity index 100% rename from packages/playground/ssr-webworker/package.json rename to playground/ssr-webworker/package.json diff --git a/packages/playground/ssr-webworker/src/entry-worker.jsx b/playground/ssr-webworker/src/entry-worker.jsx similarity index 100% rename from packages/playground/ssr-webworker/src/entry-worker.jsx rename to playground/ssr-webworker/src/entry-worker.jsx diff --git a/packages/playground/ssr-webworker/vite.config.js b/playground/ssr-webworker/vite.config.js similarity index 100% rename from packages/playground/ssr-webworker/vite.config.js rename to playground/ssr-webworker/vite.config.js diff --git a/packages/playground/ssr-webworker/worker.js b/playground/ssr-webworker/worker.js similarity index 68% rename from packages/playground/ssr-webworker/worker.js rename to playground/ssr-webworker/worker.js index 09725aaa9d71bb..e9a51e320c9899 100644 --- a/packages/playground/ssr-webworker/worker.js +++ b/playground/ssr-webworker/worker.js @@ -2,11 +2,11 @@ const path = require('path') const { Miniflare } = require('miniflare') -const isDev = process.env.DEV +const isTest = !!process.env.TEST -async function createServer(root = process.cwd()) { +async function createServer() { const mf = new Miniflare({ - scriptPath: path.resolve(root, 'dist/worker/entry-worker.js') + scriptPath: path.resolve(__dirname, 'dist/worker/entry-worker.js') }) const app = mf.createServer() @@ -14,7 +14,7 @@ async function createServer(root = process.cwd()) { return { app } } -if (isDev) { +if (!isTest) { createServer().then(({ app }) => app.listen(3000, () => { console.log('http://localhost:3000') diff --git a/playground/tailwind-sourcemap/__tests__/build.spec.ts b/playground/tailwind-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..b30284731a76d9 --- /dev/null +++ b/playground/tailwind-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,7 @@ +import { isBuild, serverLogs } from '~utils' + +test.runIf(isBuild)('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) +}) diff --git a/playground/tailwind-sourcemap/__tests__/serve.spec.ts b/playground/tailwind-sourcemap/__tests__/serve.spec.ts new file mode 100644 index 00000000000000..62e46cc7781482 --- /dev/null +++ b/playground/tailwind-sourcemap/__tests__/serve.spec.ts @@ -0,0 +1,7 @@ +import { isBuild, serverLogs } from '~utils' + +test.runIf(isBuild)('should not output missing source file warning', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch(/Sourcemap for .+ points to missing source files/) + }) +}) diff --git a/packages/playground/tailwind-sourcemap/index.html b/playground/tailwind-sourcemap/index.html similarity index 100% rename from packages/playground/tailwind-sourcemap/index.html rename to playground/tailwind-sourcemap/index.html diff --git a/packages/playground/tailwind-sourcemap/package.json b/playground/tailwind-sourcemap/package.json similarity index 68% rename from packages/playground/tailwind-sourcemap/package.json rename to playground/tailwind-sourcemap/package.json index 5c374f3bf47f1b..10c02556713d1c 100644 --- a/packages/playground/tailwind-sourcemap/package.json +++ b/playground/tailwind-sourcemap/package.json @@ -5,10 +5,10 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { - "tailwindcss": "^3.0.23" + "tailwindcss": "^3.0.24" } } diff --git a/packages/playground/tailwind-sourcemap/postcss.config.js b/playground/tailwind-sourcemap/postcss.config.js similarity index 100% rename from packages/playground/tailwind-sourcemap/postcss.config.js rename to playground/tailwind-sourcemap/postcss.config.js diff --git a/packages/playground/tailwind-sourcemap/tailwind.config.js b/playground/tailwind-sourcemap/tailwind.config.js similarity index 100% rename from packages/playground/tailwind-sourcemap/tailwind.config.js rename to playground/tailwind-sourcemap/tailwind.config.js diff --git a/packages/playground/tailwind-sourcemap/tailwind.css b/playground/tailwind-sourcemap/tailwind.css similarity index 100% rename from packages/playground/tailwind-sourcemap/tailwind.css rename to playground/tailwind-sourcemap/tailwind.css diff --git a/packages/playground/tailwind-sourcemap/vite.config.js b/playground/tailwind-sourcemap/vite.config.js similarity index 100% rename from packages/playground/tailwind-sourcemap/vite.config.js rename to playground/tailwind-sourcemap/vite.config.js diff --git a/packages/playground/tailwind/__test__/tailwind.spec.ts b/playground/tailwind/__test__/tailwind.spec.ts similarity index 94% rename from packages/playground/tailwind/__test__/tailwind.spec.ts rename to playground/tailwind/__test__/tailwind.spec.ts index 47f6b7ccf49037..ee596a17999a6e 100644 --- a/packages/playground/tailwind/__test__/tailwind.spec.ts +++ b/playground/tailwind/__test__/tailwind.spec.ts @@ -1,4 +1,11 @@ -import { isBuild, editFile, untilUpdated, getColor } from '../../testUtils' +import { + isBuild, + editFile, + untilUpdated, + getColor, + browserLogs, + page +} from '~utils' test('should render', async () => { expect(await page.textContent('#pagetitle')).toBe('|Page title|') diff --git a/packages/playground/tailwind/index.css b/playground/tailwind/index.css similarity index 100% rename from packages/playground/tailwind/index.css rename to playground/tailwind/index.css diff --git a/packages/playground/tailwind/index.html b/playground/tailwind/index.html similarity index 100% rename from packages/playground/tailwind/index.html rename to playground/tailwind/index.html diff --git a/packages/playground/tailwind/package.json b/playground/tailwind/package.json similarity index 54% rename from packages/playground/tailwind/package.json rename to playground/tailwind/package.json index ff79908d386e96..9bf1b1fbe5fff2 100644 --- a/packages/playground/tailwind/package.json +++ b/playground/tailwind/package.json @@ -5,16 +5,17 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { - "autoprefixer": "^10.4.0", + "autoprefixer": "^10.4.7", "tailwindcss": "^2.2.19", - "vue": "^3.2.25", - "vue-router": "^4.0.0" + "vue": "^3.2.33", + "vue-router": "^4.0.15" }, "devDependencies": { - "@vitejs/plugin-vue": "workspace:*" + "@vitejs/plugin-vue": "workspace:*", + "ts-node": "^10.7.0" } } diff --git a/packages/playground/tailwind/postcss.config.js b/playground/tailwind/postcss.config.ts similarity index 85% rename from packages/playground/tailwind/postcss.config.js rename to playground/tailwind/postcss.config.ts index b73493f7f96fae..381d8cbd107f81 100644 --- a/packages/playground/tailwind/postcss.config.js +++ b/playground/tailwind/postcss.config.ts @@ -1,4 +1,4 @@ -// postcss.config.js +// postcss.config.ts module.exports = { plugins: { tailwindcss: { config: __dirname + '/tailwind.config.js' }, diff --git a/packages/playground/tailwind/public/favicon.ico b/playground/tailwind/public/favicon.ico similarity index 100% rename from packages/playground/tailwind/public/favicon.ico rename to playground/tailwind/public/favicon.ico diff --git a/packages/playground/tailwind/src/App.vue b/playground/tailwind/src/App.vue similarity index 100% rename from packages/playground/tailwind/src/App.vue rename to playground/tailwind/src/App.vue diff --git a/packages/playground/tailwind/src/assets/logo.png b/playground/tailwind/src/assets/logo.png similarity index 100% rename from packages/playground/tailwind/src/assets/logo.png rename to playground/tailwind/src/assets/logo.png diff --git a/packages/playground/tailwind/src/components/HelloWorld.vue b/playground/tailwind/src/components/HelloWorld.vue similarity index 100% rename from packages/playground/tailwind/src/components/HelloWorld.vue rename to playground/tailwind/src/components/HelloWorld.vue diff --git a/packages/playground/tailwind/src/main.js b/playground/tailwind/src/main.js similarity index 100% rename from packages/playground/tailwind/src/main.js rename to playground/tailwind/src/main.js diff --git a/packages/playground/tailwind/src/router.ts b/playground/tailwind/src/router.ts similarity index 100% rename from packages/playground/tailwind/src/router.ts rename to playground/tailwind/src/router.ts diff --git a/packages/playground/tailwind/src/views/Page.vue b/playground/tailwind/src/views/Page.vue similarity index 100% rename from packages/playground/tailwind/src/views/Page.vue rename to playground/tailwind/src/views/Page.vue diff --git a/packages/playground/tailwind/tailwind.config.js b/playground/tailwind/tailwind.config.js similarity index 100% rename from packages/playground/tailwind/tailwind.config.js rename to playground/tailwind/tailwind.config.js diff --git a/packages/playground/tailwind/vite.config.ts b/playground/tailwind/vite.config.ts similarity index 100% rename from packages/playground/tailwind/vite.config.ts rename to playground/tailwind/vite.config.ts diff --git a/packages/playground/testUtils.ts b/playground/test-utils.ts similarity index 76% rename from packages/playground/testUtils.ts rename to playground/test-utils.ts index 427fea6d947a4f..47bab08b698336 100644 --- a/packages/playground/testUtils.ts +++ b/playground/test-utils.ts @@ -1,6 +1,9 @@ +/* eslint-disable @typescript-eslint/triple-slash-reference */ // test utils used in e2e tests for playgrounds. -// this can be directly imported in any playground tests as 'testUtils', e.g. -// `import { getColor } from 'testUtils'` +// `import { getColor } from '~utils'` + +// TODO: explicitly import APIs and remove this +/// import fs from 'fs' import path from 'path' @@ -9,6 +12,24 @@ import type { ElementHandle } from 'playwright-chromium' import type { Manifest } from 'vite' import { normalizePath } from 'vite' import { fromComment } from 'convert-source-map' +import { expect } from 'vitest' +import { page } from './vitestSetup' + +export * from './vitestSetup' + +export const workspaceRoot = path.resolve(__dirname, '../') + +export const isBuild = !!process.env.VITE_TEST_BUILD +export const isServe = !isBuild + +export const isWindows = process.platform === 'win32' +export const viteBinPath = path.join( + workspaceRoot, + 'packages', + 'vite', + 'bin', + 'vite.js' +) // make sure these ports are unique export const ports = { @@ -31,12 +52,11 @@ export function slash(p: string): string { return p.replace(/\\/g, '/') } -export const isBuild = !!process.env.VITE_TEST_BUILD - -const testPath = expect.getState().testPath -const testName = slash(testPath).match(/playground\/([\w-]+)\//)?.[1] -export const testDir = path.resolve(__dirname, '../../packages/temp', testName) -export const workspaceRoot = path.resolve(__dirname, '../../') +export const testDir = () => { + const testPath = expect.getState().testPath + const testName = slash(testPath).match(/playground\/([\w-]+)\//)?.[1] + return path.resolve(__dirname, '../playground-temp', testName) +} const hexToNameMap: Record = {} Object.keys(colors).forEach((color) => { @@ -89,7 +109,7 @@ export async function getBgColor(el: string | ElementHandle): Promise { } export function readFile(filename: string): string { - return fs.readFileSync(path.resolve(testDir, filename), 'utf-8') + return fs.readFileSync(path.resolve(testDir(), filename), 'utf-8') } export function editFile( @@ -98,27 +118,27 @@ export function editFile( runInBuild: boolean = false ): void { if (isBuild && !runInBuild) return - filename = path.resolve(testDir, filename) + filename = path.resolve(testDir(), filename) const content = fs.readFileSync(filename, 'utf-8') const modified = replacer(content) fs.writeFileSync(filename, modified) } export function addFile(filename: string, content: string): void { - fs.writeFileSync(path.resolve(testDir, filename), content) + fs.writeFileSync(path.resolve(testDir(), filename), content) } export function removeFile(filename: string): void { - fs.unlinkSync(path.resolve(testDir, filename)) + fs.unlinkSync(path.resolve(testDir(), filename)) } export function listAssets(base = ''): string[] { - const assetsDir = path.join(testDir, 'dist', base, 'assets') + const assetsDir = path.join(testDir(), 'dist', base, 'assets') return fs.readdirSync(assetsDir) } export function findAssetFile(match: string | RegExp, base = ''): string { - const assetsDir = path.join(testDir, 'dist', base, 'assets') + const assetsDir = path.join(testDir(), 'dist', base, 'assets') const files = fs.readdirSync(assetsDir) const file = files.find((file) => { return file.match(match) @@ -128,7 +148,10 @@ export function findAssetFile(match: string | RegExp, base = ''): string { export function readManifest(base = ''): Manifest { return JSON.parse( - fs.readFileSync(path.join(testDir, 'dist', base, 'manifest.json'), 'utf-8') + fs.readFileSync( + path.join(testDir(), 'dist', base, 'manifest.json'), + 'utf-8' + ) ) } @@ -153,18 +176,13 @@ export async function untilUpdated( } } -/** - * Send the rebuild complete message in build watch - */ -export { notifyRebuildComplete } from '../../scripts/jestPerTestSetup' - export const extractSourcemap = (content: string) => { const lines = content.trim().split('\n') return fromComment(lines[lines.length - 1]).toObject() } export const formatSourcemapForSnapshot = (map: any) => { - const root = normalizePath(testDir) + const root = normalizePath(testDir()) const m = { ...map } delete m.file delete m.names diff --git a/packages/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts b/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts similarity index 85% rename from packages/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts rename to playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts index 699f658da6a255..52a02683b79c00 100644 --- a/packages/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts +++ b/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts @@ -1,13 +1,23 @@ -import { editFile, isBuild, readFile, untilUpdated } from '../../testUtils' +import { + beforeAllError, + browserLogs, + clearBeforeAllError, + editFile, + isBuild, + isServe, + page, + readFile, + untilUpdated +} from '~utils' -if (isBuild) { +describe.runIf(isBuild)('build', () => { test('should throw an error on build', () => { const buildError = beforeAllError expect(buildError).toBeTruthy() expect(buildError.message).toMatch( /^parsing .* failed: SyntaxError: Unexpected token } in JSON at position \d+$/ ) - beforeAllError = null // got expected error, null it here so testsuite does not fail from rethrow in afterAll + clearBeforeAllError() // got expected error, null it here so testsuite does not fail from rethrow in afterAll }) test('should not output files to dist', () => { @@ -20,7 +30,9 @@ if (isBuild) { expect(err).toBeTruthy() expect(err.code).toBe('ENOENT') }) -} else { +}) + +describe.runIf(isServe)('server', () => { test('should log 500 error in browser for malformed tsconfig', () => { // don't test for actual complete message as this might be locale dependant. chrome does log 500 consistently though expect(browserLogs.find((x) => x.includes('500'))).toBeTruthy() @@ -47,4 +59,4 @@ if (isBuild) { return browserLogs.find((x) => x === 'tsconfig error fixed, file loaded') }, 'tsconfig error fixed, file loaded') }) -} +}) diff --git a/packages/playground/tsconfig-json-load-error/has-error/main.ts b/playground/tsconfig-json-load-error/has-error/main.ts similarity index 100% rename from packages/playground/tsconfig-json-load-error/has-error/main.ts rename to playground/tsconfig-json-load-error/has-error/main.ts diff --git a/packages/playground/tsconfig-json-load-error/has-error/tsconfig.json b/playground/tsconfig-json-load-error/has-error/tsconfig.json similarity index 100% rename from packages/playground/tsconfig-json-load-error/has-error/tsconfig.json rename to playground/tsconfig-json-load-error/has-error/tsconfig.json diff --git a/packages/playground/tsconfig-json-load-error/index.html b/playground/tsconfig-json-load-error/index.html similarity index 100% rename from packages/playground/tsconfig-json-load-error/index.html rename to playground/tsconfig-json-load-error/index.html diff --git a/packages/playground/tsconfig-json-load-error/package.json b/playground/tsconfig-json-load-error/package.json similarity index 73% rename from packages/playground/tsconfig-json-load-error/package.json rename to playground/tsconfig-json-load-error/package.json index b02c6e5ee5ab53..b518a721d9ee62 100644 --- a/packages/playground/tsconfig-json-load-error/package.json +++ b/playground/tsconfig-json-load-error/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/tsconfig-json-load-error/src/main.ts b/playground/tsconfig-json-load-error/src/main.ts similarity index 100% rename from packages/playground/tsconfig-json-load-error/src/main.ts rename to playground/tsconfig-json-load-error/src/main.ts diff --git a/packages/playground/tsconfig-json-load-error/tsconfig.json b/playground/tsconfig-json-load-error/tsconfig.json similarity index 100% rename from packages/playground/tsconfig-json-load-error/tsconfig.json rename to playground/tsconfig-json-load-error/tsconfig.json diff --git a/packages/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts b/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts similarity index 98% rename from packages/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts rename to playground/tsconfig-json/__tests__/tsconfig-json.spec.ts index 0cd6af909f045b..aec0c42b3a3a77 100644 --- a/packages/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts +++ b/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts @@ -1,6 +1,7 @@ import path from 'path' import fs from 'fs' import { transformWithEsbuild } from 'vite' +import { browserLogs } from '~utils' test('should respected each `tsconfig.json`s compilerOptions', () => { // main side effect should be called (because of `"importsNotUsedAsValues": "preserve"`) diff --git a/packages/playground/tsconfig-json/index.html b/playground/tsconfig-json/index.html similarity index 100% rename from packages/playground/tsconfig-json/index.html rename to playground/tsconfig-json/index.html diff --git a/packages/playground/tsconfig-json/nested-with-extends/main.ts b/playground/tsconfig-json/nested-with-extends/main.ts similarity index 100% rename from packages/playground/tsconfig-json/nested-with-extends/main.ts rename to playground/tsconfig-json/nested-with-extends/main.ts diff --git a/packages/playground/tsconfig-json/nested-with-extends/not-used-type.ts b/playground/tsconfig-json/nested-with-extends/not-used-type.ts similarity index 100% rename from packages/playground/tsconfig-json/nested-with-extends/not-used-type.ts rename to playground/tsconfig-json/nested-with-extends/not-used-type.ts diff --git a/packages/playground/tsconfig-json/nested-with-extends/tsconfig.json b/playground/tsconfig-json/nested-with-extends/tsconfig.json similarity index 100% rename from packages/playground/tsconfig-json/nested-with-extends/tsconfig.json rename to playground/tsconfig-json/nested-with-extends/tsconfig.json diff --git a/packages/playground/tsconfig-json/nested/main.ts b/playground/tsconfig-json/nested/main.ts similarity index 100% rename from packages/playground/tsconfig-json/nested/main.ts rename to playground/tsconfig-json/nested/main.ts diff --git a/packages/playground/tsconfig-json/nested/not-used-type.ts b/playground/tsconfig-json/nested/not-used-type.ts similarity index 100% rename from packages/playground/tsconfig-json/nested/not-used-type.ts rename to playground/tsconfig-json/nested/not-used-type.ts diff --git a/packages/playground/tsconfig-json/nested/tsconfig.json b/playground/tsconfig-json/nested/tsconfig.json similarity index 100% rename from packages/playground/tsconfig-json/nested/tsconfig.json rename to playground/tsconfig-json/nested/tsconfig.json diff --git a/packages/playground/tsconfig-json/package.json b/playground/tsconfig-json/package.json similarity index 72% rename from packages/playground/tsconfig-json/package.json rename to playground/tsconfig-json/package.json index c4248463facdb9..f236dbdc5fe77c 100644 --- a/packages/playground/tsconfig-json/package.json +++ b/playground/tsconfig-json/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" } } diff --git a/packages/playground/tsconfig-json/src/main.ts b/playground/tsconfig-json/src/main.ts similarity index 100% rename from packages/playground/tsconfig-json/src/main.ts rename to playground/tsconfig-json/src/main.ts diff --git a/packages/playground/tsconfig-json/src/not-used-type.ts b/playground/tsconfig-json/src/not-used-type.ts similarity index 100% rename from packages/playground/tsconfig-json/src/not-used-type.ts rename to playground/tsconfig-json/src/not-used-type.ts diff --git a/packages/playground/tsconfig-json/tsconfig.json b/playground/tsconfig-json/tsconfig.json similarity index 100% rename from packages/playground/tsconfig-json/tsconfig.json rename to playground/tsconfig-json/tsconfig.json diff --git a/packages/playground/tsconfig.json b/playground/tsconfig.json similarity index 53% rename from packages/playground/tsconfig.json rename to playground/tsconfig.json index d60edb9f78c801..ada2a60bff6cff 100644 --- a/packages/playground/tsconfig.json +++ b/playground/tsconfig.json @@ -3,12 +3,19 @@ "exclude": ["**/dist/**"], "compilerOptions": { "target": "es2019", + "module": "esnext", "outDir": "dist", + "baseUrl": ".", "allowJs": true, "esModuleInterop": true, + "resolveJsonModule": true, "moduleResolution": "node", - "baseUrl": ".", + "skipLibCheck": true, + "noUnusedLocals": true, "jsx": "preserve", - "types": ["vite/client", "jest", "node"] + "types": ["vite/client", "vitest/globals", "node"], + "paths": { + "~utils": ["./test-utils.ts"] + } } } diff --git a/scripts/jestGlobalSetup.cjs b/playground/vitestGlobalSetup.ts similarity index 54% rename from scripts/jestGlobalSetup.cjs rename to playground/vitestGlobalSetup.ts index 7341cba40968d9..52b49d01f38fda 100644 --- a/scripts/jestGlobalSetup.cjs +++ b/playground/vitestGlobalSetup.ts @@ -1,28 +1,29 @@ -// @ts-check -const os = require('os') -const fs = require('fs-extra') -const path = require('path') -const { chromium } = require('playwright-chromium') +import os from 'os' +import path from 'path' +import fs from 'fs-extra' +import type { BrowserServer } from 'playwright-chromium' +import { chromium } from 'playwright-chromium' -const DIR = path.join(os.tmpdir(), 'jest_playwright_global_setup') +const DIR = path.join(os.tmpdir(), 'vitest_playwright_global_setup') -module.exports = async () => { - const browserServer = await chromium.launchServer({ +let browserServer: BrowserServer | undefined + +export async function setup() { + browserServer = await chromium.launchServer({ headless: !process.env.VITE_DEBUG_SERVE, args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : undefined }) - global.__BROWSER_SERVER__ = browserServer - await fs.mkdirp(DIR) await fs.writeFile(path.join(DIR, 'wsEndpoint'), browserServer.wsEndpoint()) - const tempDir = path.resolve(__dirname, '../packages/temp') - await fs.remove(tempDir) + const tempDir = path.resolve(__dirname, '../playground-temp') + await fs.ensureDir(tempDir) + await fs.emptyDir(tempDir) await fs - .copy(path.resolve(__dirname, '../packages/playground'), tempDir, { + .copy(path.resolve(__dirname, '../playground'), tempDir, { dereference: false, filter(file) { file = file.replace(/\\/g, '/') @@ -39,3 +40,10 @@ module.exports = async () => { } }) } + +export async function teardown() { + browserServer?.close() + if (!process.env.VITE_PRESERVE_BUILD_ARTIFACTS) { + fs.removeSync(path.resolve(__dirname, '../playground-temp')) + } +} diff --git a/scripts/jestPerTestSetup.ts b/playground/vitestSetup.ts similarity index 64% rename from scripts/jestPerTestSetup.ts rename to playground/vitestSetup.ts index f4c9db03627c7c..4734f561a73701 100644 --- a/scripts/jestPerTestSetup.ts +++ b/playground/vitestSetup.ts @@ -1,94 +1,111 @@ -import fs from 'fs-extra' import * as http from 'http' -import { resolve, dirname } from 'path' +import { dirname, resolve } from 'path' +import os from 'os' +import path from 'path' import sirv from 'sirv' +import fs from 'fs-extra' +import { chromium } from 'playwright-chromium' import type { - ViteDevServer, InlineConfig, + Logger, PluginOption, ResolvedConfig, - Logger + ViteDevServer } from 'vite' -import { createServer, build, mergeConfig } from 'vite' -import type { Page, ConsoleMessage } from 'playwright-chromium' +import { build, createServer, mergeConfig } from 'vite' +import type { Browser, Page } from 'playwright-chromium' import type { RollupError, RollupWatcher, RollupWatcherEvent } from 'rollup' +import type { File } from 'vitest' +import { beforeAll } from 'vitest' const isBuildTest = !!process.env.VITE_TEST_BUILD -export function slash(p: string): string { - return p.replace(/\\/g, '/') -} +let server: ViteDevServer | http.Server +let tempDir: string +let rootDir: string -// injected by the test env -declare global { - const page: Page | undefined +export const serverLogs: string[] = [] +export const browserLogs: string[] = [] +export const browserErrors: Error[] = [] - const browserLogs: string[] - const browserErrors: Error[] - const serverLogs: string[] - const viteTestUrl: string | undefined - const watcher: RollupWatcher | undefined - let beforeAllError: Error | null // error caught in beforeAll, useful if you want to test error scenarios on build -} +/** + * Error caught in beforeAll, useful if you want to test error scenarios on build + */ +export let beforeAllError: Error | null = null -declare const global: { - page?: Page +export let page: Page = undefined! +export let browser: Browser = undefined! +export let viteTestUrl: string = '' +export let watcher: RollupWatcher | undefined = undefined - browserLogs: string[] - browserErrors: Error[] - serverLogs: string[] - viteTestUrl?: string - watcher?: RollupWatcher - beforeAllError: Error | null +export function clearBeforeAllError() { + beforeAllError = null } -let server: ViteDevServer | http.Server -let tempDir: string -let rootDir: string - -const setBeforeAllError = (err: Error | null) => { - global.beforeAllError = err +export function setViteUrl(url: string) { + viteTestUrl = url } -const getBeforeAllError = () => global.beforeAllError -//init with null so old errors don't carry over -setBeforeAllError(null) -const logs: string[] = (global.browserLogs = []) -const onConsole = (msg: ConsoleMessage) => { - logs.push(msg.text()) +export function slash(p: string): string { + return p.replace(/\\/g, '/') } -const errors: Error[] = (global.browserErrors = []) -const onPageError = (error: Error) => { - errors.push(error) -} +const DIR = path.join(os.tmpdir(), 'vitest_playwright_global_setup') + +beforeAll(async (s) => { + const suite = s as File + const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf-8') + if (!wsEndpoint) { + throw new Error('wsEndpoint not found') + } -beforeAll(async () => { - const page = global.page - if (!page) { + // skip browser setup for non-playground tests + if (!suite.filepath.includes('playground')) { return } + + browser = await chromium.connect(wsEndpoint) + page = await browser.newPage() + + const globalConsole = globalThis.console + const warn = globalConsole.warn + globalConsole.warn = (msg, ...args) => { + // suppress @vue/reactivity-transform warning + if (msg.includes('@vue/reactivity-transform')) return + if (msg.includes('Generated an empty chunk')) return + warn.call(globalConsole, msg, ...args) + } + try { - page.on('console', onConsole) - page.on('pageerror', onPageError) + page.on('console', (msg) => { + browserLogs.push(msg.text()) + }) + page.on('pageerror', (error) => { + browserErrors.push(error) + }) - const testPath = expect.getState().testPath + const testPath = suite.filepath! const testName = slash(testPath).match(/playground\/([\w-]+)\//)?.[1] // if this is a test placed under playground/xxx/__tests__ // start a vite server in that directory. if (testName) { - const playgroundRoot = resolve(__dirname, '../packages/playground') - tempDir = resolve(__dirname, '../packages/temp/', testName) + tempDir = resolve(__dirname, '../playground-temp/', testName) // when `root` dir is present, use it as vite's root const testCustomRoot = resolve(tempDir, 'root') rootDir = fs.existsSync(testCustomRoot) ? testCustomRoot : tempDir - const testCustomServe = resolve(dirname(testPath), 'serve.js') - if (fs.existsSync(testCustomServe)) { + const testCustomServe = [ + resolve(dirname(testPath), 'serve.ts'), + resolve(dirname(testPath), 'serve.cjs'), + resolve(dirname(testPath), 'serve.js') + ].find((i) => fs.existsSync(i)) + if (testCustomServe) { // test has custom server configuration. - const { serve, preServe } = require(testCustomServe) + const mod = await import(testCustomServe) + const serve = mod.serve || mod.default?.serve + const preServe = mod.preServe || mod.default?.preServe if (preServe) { await preServe(rootDir, isBuildTest) } @@ -105,8 +122,6 @@ beforeAll(async () => { config = require(testCustomConfig) } - const serverLogs: string[] = [] - const options: InlineConfig = { root: rootDir, logLevel: 'silent', @@ -132,8 +147,6 @@ beforeAll(async () => { setupConsoleWarnCollector(serverLogs) - global.serverLogs = serverLogs - if (!isBuildTest) { process.env.VITE_INLINE = 'inline-serve' server = await ( @@ -141,9 +154,8 @@ beforeAll(async () => { ).listen() // use resolved port/base from server const base = server.config.base === '/' ? '' : server.config.base - const url = - (global.viteTestUrl = `http://localhost:${server.config.server.port}${base}`) - await page.goto(url) + viteTestUrl = `http://localhost:${server.config.server.port}${base}` + await page.goto(viteTestUrl) } else { process.env.VITE_INLINE = 'inline-build' // determine build watch @@ -159,35 +171,33 @@ beforeAll(async () => { const isWatch = !!resolvedConfig!.build.watch // in build watch,call startStaticServer after the build is complete if (isWatch) { - global.watcher = rollupOutput as RollupWatcher - await notifyRebuildComplete(global.watcher) + watcher = rollupOutput as RollupWatcher + await notifyRebuildComplete(watcher) } - const url = (global.viteTestUrl = await startStaticServer(config)) - await page.goto(url) + viteTestUrl = await startStaticServer(config) + await page.goto(viteTestUrl) } } } catch (e: any) { - // jest doesn't exit if our setup has error here - // https://github.com/facebook/jest/issues/2713 - setBeforeAllError(e) - // Closing the page since an error in the setup, for example a runtime error // when building the playground should skip further tests. // If the page remains open, a command like `await page.click(...)` produces // a timeout with an exception that hides the real error in the console. await page.close() + beforeAllError = e } -}, 30000) - -afterAll(async () => { - global.page?.off('console', onConsole) - global.serverLogs = [] - await global.page?.close() - await server?.close() - global.watcher?.close() - const beforeAllErr = getBeforeAllError() - if (beforeAllErr) { - throw beforeAllErr + + return async () => { + serverLogs.length = 0 + await page?.close() + await server?.close() + watcher?.close() + if (browser) { + await browser.close() + } + if (beforeAllError) { + throw beforeAllError + } } }) @@ -243,14 +253,15 @@ function startStaticServer(config?: InlineConfig): Promise { export async function notifyRebuildComplete( watcher: RollupWatcher ): Promise { - let callback: (event: RollupWatcherEvent) => void - await new Promise((resolve, reject) => { - callback = (event) => { - if (event.code === 'END') { - resolve() - } + let resolveFn: undefined | (() => void) + const callback = (event: RollupWatcherEvent): void => { + if (event.code === 'END') { + resolveFn?.() } - watcher.on('event', callback) + } + watcher.on('event', callback) + await new Promise((resolve) => { + resolveFn = resolve }) return watcher.removeListener('event', callback) } diff --git a/packages/playground/vue-jsx/Comp.tsx b/playground/vue-jsx/Comp.tsx similarity index 100% rename from packages/playground/vue-jsx/Comp.tsx rename to playground/vue-jsx/Comp.tsx diff --git a/packages/playground/vue-jsx/Comps.jsx b/playground/vue-jsx/Comps.jsx similarity index 100% rename from packages/playground/vue-jsx/Comps.jsx rename to playground/vue-jsx/Comps.jsx diff --git a/packages/playground/vue-jsx/OtherExt.tesx b/playground/vue-jsx/OtherExt.tesx similarity index 100% rename from packages/playground/vue-jsx/OtherExt.tesx rename to playground/vue-jsx/OtherExt.tesx diff --git a/packages/playground/vue-jsx/Query.jsx b/playground/vue-jsx/Query.jsx similarity index 100% rename from packages/playground/vue-jsx/Query.jsx rename to playground/vue-jsx/Query.jsx diff --git a/packages/playground/vue-jsx/Script.vue b/playground/vue-jsx/Script.vue similarity index 100% rename from packages/playground/vue-jsx/Script.vue rename to playground/vue-jsx/Script.vue diff --git a/packages/playground/vue-jsx/SrcImport.jsx b/playground/vue-jsx/SrcImport.jsx similarity index 100% rename from packages/playground/vue-jsx/SrcImport.jsx rename to playground/vue-jsx/SrcImport.jsx diff --git a/packages/playground/vue-jsx/SrcImport.vue b/playground/vue-jsx/SrcImport.vue similarity index 100% rename from packages/playground/vue-jsx/SrcImport.vue rename to playground/vue-jsx/SrcImport.vue diff --git a/playground/vue-jsx/TsImport.vue b/playground/vue-jsx/TsImport.vue new file mode 100644 index 00000000000000..c63923d51947fa --- /dev/null +++ b/playground/vue-jsx/TsImport.vue @@ -0,0 +1,8 @@ + + + diff --git a/playground/vue-jsx/TsImportFile.ts b/playground/vue-jsx/TsImportFile.ts new file mode 100644 index 00000000000000..62761d5733b432 --- /dev/null +++ b/playground/vue-jsx/TsImportFile.ts @@ -0,0 +1 @@ +export const foo = 'success' diff --git a/packages/playground/vue-jsx/__tests__/vue-jsx.spec.ts b/playground/vue-jsx/__tests__/vue-jsx.spec.ts similarity index 95% rename from packages/playground/vue-jsx/__tests__/vue-jsx.spec.ts rename to playground/vue-jsx/__tests__/vue-jsx.spec.ts index 999fdc19af51ec..2e6858dacce3c4 100644 --- a/packages/playground/vue-jsx/__tests__/vue-jsx.spec.ts +++ b/playground/vue-jsx/__tests__/vue-jsx.spec.ts @@ -1,4 +1,4 @@ -import { editFile, isBuild, untilUpdated } from 'testUtils' +import { editFile, isServe, page, untilUpdated } from '~utils' test('should render', async () => { expect(await page.textContent('.named')).toMatch('0') @@ -9,6 +9,7 @@ test('should render', async () => { expect(await page.textContent('.src-import')).toMatch('5') expect(await page.textContent('.jsx-with-query')).toMatch('6') expect(await page.textContent('.other-ext')).toMatch('Other Ext') + expect(await page.textContent('.ts-import')).toMatch('success') }) test('should update', async () => { @@ -28,7 +29,7 @@ test('should update', async () => { expect(await page.textContent('.jsx-with-query')).toMatch('7') }) -if (!isBuild) { +describe.runIf(isServe)('vue-jsx server', () => { test('hmr: named export', async () => { editFile('Comps.jsx', (code) => code.replace('named {count', 'named updated {count') @@ -112,4 +113,4 @@ if (!isBuild) { ) await untilUpdated(() => page.textContent('.setup-jsx'), '1000') }) -} +}) diff --git a/packages/playground/vue-jsx/index.html b/playground/vue-jsx/index.html similarity index 100% rename from packages/playground/vue-jsx/index.html rename to playground/vue-jsx/index.html diff --git a/packages/playground/vue-jsx/main.jsx b/playground/vue-jsx/main.jsx similarity index 92% rename from packages/playground/vue-jsx/main.jsx rename to playground/vue-jsx/main.jsx index e304e7788e49e7..f13e60c45367c0 100644 --- a/packages/playground/vue-jsx/main.jsx +++ b/playground/vue-jsx/main.jsx @@ -7,6 +7,7 @@ import JsxSrcImport from './SrcImport.vue' import JsxSetupSyntax from './setup-syntax-jsx.vue' // eslint-disable-next-line import JsxWithQuery from './Query.jsx?query=true' +import TsImport from './TsImport.vue' function App() { return ( @@ -20,6 +21,7 @@ function App() { + ) } diff --git a/packages/playground/vue-jsx/package.json b/playground/vue-jsx/package.json similarity index 78% rename from packages/playground/vue-jsx/package.json rename to playground/vue-jsx/package.json index 4b2135906b2833..697b9f312fd9b1 100644 --- a/packages/playground/vue-jsx/package.json +++ b/playground/vue-jsx/package.json @@ -5,11 +5,11 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { - "vue": "^3.2.25" + "vue": "^3.2.33" }, "devDependencies": { "@vitejs/plugin-vue": "workspace:*", diff --git a/packages/playground/vue-jsx/setup-syntax-jsx.vue b/playground/vue-jsx/setup-syntax-jsx.vue similarity index 100% rename from packages/playground/vue-jsx/setup-syntax-jsx.vue rename to playground/vue-jsx/setup-syntax-jsx.vue diff --git a/packages/playground/vue-jsx/vite.config.js b/playground/vue-jsx/vite.config.js similarity index 100% rename from packages/playground/vue-jsx/vite.config.js rename to playground/vue-jsx/vite.config.js diff --git a/playground/vue-lib/__tests__/serve.ts b/playground/vue-lib/__tests__/serve.ts new file mode 100644 index 00000000000000..70d30af178f50e --- /dev/null +++ b/playground/vue-lib/__tests__/serve.ts @@ -0,0 +1,6 @@ +// this is automatically detected by playground/vitestSetup.ts and will replace +// the default e2e test serve behavior + +export async function serve() { + // do nothing, skip default behavior +} diff --git a/packages/playground/vue-lib/__tests__/vue-lib.spec.ts b/playground/vue-lib/__tests__/vue-lib.spec.ts similarity index 100% rename from packages/playground/vue-lib/__tests__/vue-lib.spec.ts rename to playground/vue-lib/__tests__/vue-lib.spec.ts index 0504160f17d2f0..5766b0c0c5643a 100644 --- a/packages/playground/vue-lib/__tests__/vue-lib.spec.ts +++ b/playground/vue-lib/__tests__/vue-lib.spec.ts @@ -1,5 +1,5 @@ -import { build } from 'vite' import path from 'path' +import { build } from 'vite' import type { OutputChunk, RollupOutput } from 'rollup' describe('vue component library', () => { diff --git a/packages/playground/vue-lib/index.html b/playground/vue-lib/index.html similarity index 100% rename from packages/playground/vue-lib/index.html rename to playground/vue-lib/index.html diff --git a/packages/playground/vue-lib/package.json b/playground/vue-lib/package.json similarity index 94% rename from packages/playground/vue-lib/package.json rename to playground/vue-lib/package.json index df82cf48b62a9c..684e5ea83cb429 100644 --- a/packages/playground/vue-lib/package.json +++ b/playground/vue-lib/package.json @@ -8,7 +8,7 @@ "build-consumer": "vite build --config ./vite.config.consumer.ts" }, "dependencies": { - "vue": "^3.2.25" + "vue": "^3.2.33" }, "devDependencies": { "@vitejs/plugin-vue": "workspace:*" diff --git a/packages/playground/vue-lib/src-consumer/index.ts b/playground/vue-lib/src-consumer/index.ts similarity index 100% rename from packages/playground/vue-lib/src-consumer/index.ts rename to playground/vue-lib/src-consumer/index.ts index ac0f65e2a3ed9d..ee20f81d75a7ca 100644 --- a/packages/playground/vue-lib/src-consumer/index.ts +++ b/playground/vue-lib/src-consumer/index.ts @@ -1,5 +1,5 @@ -// @ts-ignore /* eslint-disable node/no-missing-import */ +// @ts-ignore import { CompA } from '../dist/lib/my-vue-lib.es' import '../dist/lib/style.css' import { createApp } from 'vue' diff --git a/packages/playground/vue-lib/src-lib/CompA.vue b/playground/vue-lib/src-lib/CompA.vue similarity index 100% rename from packages/playground/vue-lib/src-lib/CompA.vue rename to playground/vue-lib/src-lib/CompA.vue diff --git a/packages/playground/vue-lib/src-lib/CompB.vue b/playground/vue-lib/src-lib/CompB.vue similarity index 100% rename from packages/playground/vue-lib/src-lib/CompB.vue rename to playground/vue-lib/src-lib/CompB.vue diff --git a/packages/playground/vue-lib/src-lib/index.ts b/playground/vue-lib/src-lib/index.ts similarity index 100% rename from packages/playground/vue-lib/src-lib/index.ts rename to playground/vue-lib/src-lib/index.ts diff --git a/packages/playground/vue-lib/vite.config.consumer.ts b/playground/vue-lib/vite.config.consumer.ts similarity index 100% rename from packages/playground/vue-lib/vite.config.consumer.ts rename to playground/vue-lib/vite.config.consumer.ts diff --git a/packages/playground/vue-lib/vite.config.lib.ts b/playground/vue-lib/vite.config.lib.ts similarity index 89% rename from packages/playground/vue-lib/vite.config.lib.ts rename to playground/vue-lib/vite.config.lib.ts index a888382d008a8c..0cc082c7ceea85 100644 --- a/packages/playground/vue-lib/vite.config.lib.ts +++ b/playground/vue-lib/vite.config.lib.ts @@ -10,7 +10,7 @@ export default defineConfig({ entry: path.resolve(__dirname, 'src-lib/index.ts'), name: 'MyVueLib', formats: ['es'], - fileName: (format) => `my-vue-lib.${format}.js` + fileName: 'my-vue-lib' }, rollupOptions: { external: ['vue'], diff --git a/packages/playground/vue-sourcemap/Css.vue b/playground/vue-sourcemap/Css.vue similarity index 63% rename from packages/playground/vue-sourcemap/Css.vue rename to playground/vue-sourcemap/Css.vue index 19668de8d33965..4f677c7b84dfbd 100644 --- a/packages/playground/vue-sourcemap/Css.vue +++ b/playground/vue-sourcemap/Css.vue @@ -2,6 +2,7 @@

<css>

<css> module

<css> scoped

+

<css> scoped with nested

+ + diff --git a/packages/playground/vue-sourcemap/Js.vue b/playground/vue-sourcemap/Js.vue similarity index 100% rename from packages/playground/vue-sourcemap/Js.vue rename to playground/vue-sourcemap/Js.vue diff --git a/packages/playground/vue-sourcemap/Less.vue b/playground/vue-sourcemap/Less.vue similarity index 100% rename from packages/playground/vue-sourcemap/Less.vue rename to playground/vue-sourcemap/Less.vue diff --git a/packages/playground/vue-sourcemap/Main.vue b/playground/vue-sourcemap/Main.vue similarity index 100% rename from packages/playground/vue-sourcemap/Main.vue rename to playground/vue-sourcemap/Main.vue diff --git a/packages/playground/vue-sourcemap/Sass.vue b/playground/vue-sourcemap/Sass.vue similarity index 100% rename from packages/playground/vue-sourcemap/Sass.vue rename to playground/vue-sourcemap/Sass.vue diff --git a/packages/playground/vue-sourcemap/SassWithImport.vue b/playground/vue-sourcemap/SassWithImport.vue similarity index 100% rename from packages/playground/vue-sourcemap/SassWithImport.vue rename to playground/vue-sourcemap/SassWithImport.vue diff --git a/packages/playground/vue-sourcemap/Ts.vue b/playground/vue-sourcemap/Ts.vue similarity index 100% rename from packages/playground/vue-sourcemap/Ts.vue rename to playground/vue-sourcemap/Ts.vue diff --git a/playground/vue-sourcemap/__tests__/build.spec.ts b/playground/vue-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..b30284731a76d9 --- /dev/null +++ b/playground/vue-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,7 @@ +import { isBuild, serverLogs } from '~utils' + +test.runIf(isBuild)('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) +}) diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/playground/vue-sourcemap/__tests__/serve.spec.ts similarity index 79% rename from packages/playground/vue-sourcemap/__tests__/serve.spec.ts rename to playground/vue-sourcemap/__tests__/serve.spec.ts index 08b4c04face111..278b04bef1e6f5 100644 --- a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts +++ b/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -1,11 +1,12 @@ +import { URL } from 'url' import { extractSourcemap, formatSourcemapForSnapshot, - isBuild -} from 'testUtils' -import { URL } from 'url' + isServe, + page +} from '~utils' -if (!isBuild) { +describe.runIf(isServe)('serve:vue-sourcemap', () => { const getStyleTagContentIncluding = async (content: string) => { const styles = await page.$$('style') for (const style of styles) { @@ -22,12 +23,12 @@ if (!isBuild) { const js = await res.text() const map = extractSourcemap(js) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAKA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;AAGP;AACd,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;;;;;wBARlB,oBAAiB,WAAd,MAAU", - "sources": Array [ + "sources": [ "/root/Js.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " @@ -51,12 +52,12 @@ if (!isBuild) { const js = await res.text() const map = extractSourcemap(js) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": ";AAKA,QAAQ,IAAI,WAAW;;;;AAIvB,YAAQ,IAAI,UAAU;;;;;;;;uBARpB,oBAAiB,WAAd,MAAU", - "sources": Array [ + "sources": [ "/root/Ts.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " @@ -79,16 +80,17 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.css ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { - "mappings": ";AAOA;EACE,UAAU;AACZ", - "sources": Array [ + { + "mappings": ";AAQA;EACE,UAAU;AACZ", + "sources": [ "/root/Css.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " + + ", ], "version": 3, @@ -119,16 +131,17 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('._css-module_') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { - "mappings": ";AAaA;EACE,UAAU;AACZ", - "sources": Array [ + { + "mappings": ";AAcA;EACE,UAAU;AACZ", + "sources": [ "/root/Css.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " + + ", ], "version": 3, @@ -159,16 +182,17 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.css-scoped[data-v-') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { - "mappings": ";AAmBA;EACE,UAAU;AACZ", - "sources": Array [ + { + "mappings": ";AAoBA;EACE,UAAU;AACZ", + "sources": [ "/root/Css.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " + + ", ], "version": 3, @@ -199,12 +233,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.sass ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAKA;EACE", - "sources": Array [ + "sources": [ "/root/Sass.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " @@ -224,13 +258,13 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.sass-with-import ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA;EACE;;ACOF;EACE", - "sources": Array [ + "sources": [ "/root/sassWithImportImported.sass", "/root/SassWithImport.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ ".sass-with-import-imported color: red ", @@ -256,12 +290,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.less ') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAKA;EACE", - "sources": Array [ + "sources": [ "/root/Less.vue", ], - "sourcesContent": Array [ + "sourcesContent": [ " @@ -282,12 +316,12 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.src-import[data-v-') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA;EACE,UAAU;AACZ", - "sources": Array [ + "sources": [ "/root/src-import/src-import.css", ], - "sourcesContent": Array [ + "sourcesContent": [ ".src-import { color: red; } @@ -302,13 +336,13 @@ if (!isBuild) { const css = await getStyleTagContentIncluding('.src-import-sass[data-v-') const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { + { "mappings": "AAAA;EACE;;ACCF;EACE", - "sources": Array [ + "sources": [ "/root/src-import/src-import-imported.sass", "/root/src-import/src-import.sass", ], - "sourcesContent": Array [ + "sourcesContent": [ ".src-import-sass-imported color: red ", @@ -322,8 +356,4 @@ if (!isBuild) { } `) }) -} else { - test('this file only includes test for serve', () => { - expect(true).toBe(true) - }) -} +}) diff --git a/packages/playground/vue-sourcemap/index.html b/playground/vue-sourcemap/index.html similarity index 100% rename from packages/playground/vue-sourcemap/index.html rename to playground/vue-sourcemap/index.html diff --git a/packages/playground/vue-sourcemap/package.json b/playground/vue-sourcemap/package.json similarity index 67% rename from packages/playground/vue-sourcemap/package.json rename to playground/vue-sourcemap/package.json index 286940b01efa58..55b4deef42c77d 100644 --- a/packages/playground/vue-sourcemap/package.json +++ b/playground/vue-sourcemap/package.json @@ -5,15 +5,16 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "devDependencies": { "@vitejs/plugin-vue": "workspace:*", "less": "^4.1.2", - "sass": "^1.43.4" + "postcss-nested": "^5.0.6", + "sass": "^1.51.0" }, "dependencies": { - "vue": "^3.2.31" + "vue": "^3.2.33" } } diff --git a/playground/vue-sourcemap/postcss.config.js b/playground/vue-sourcemap/postcss.config.js new file mode 100644 index 00000000000000..9ea26b495d91b5 --- /dev/null +++ b/playground/vue-sourcemap/postcss.config.js @@ -0,0 +1,3 @@ +module.exports = { + plugins: [require('postcss-nested')] +} diff --git a/packages/playground/vue-sourcemap/sassWithImportImported.sass b/playground/vue-sourcemap/sassWithImportImported.sass similarity index 100% rename from packages/playground/vue-sourcemap/sassWithImportImported.sass rename to playground/vue-sourcemap/sassWithImportImported.sass diff --git a/packages/playground/vue-sourcemap/src-import/SrcImport.vue b/playground/vue-sourcemap/src-import/SrcImport.vue similarity index 100% rename from packages/playground/vue-sourcemap/src-import/SrcImport.vue rename to playground/vue-sourcemap/src-import/SrcImport.vue diff --git a/packages/playground/vue-sourcemap/src-import/src-import-imported.sass b/playground/vue-sourcemap/src-import/src-import-imported.sass similarity index 100% rename from packages/playground/vue-sourcemap/src-import/src-import-imported.sass rename to playground/vue-sourcemap/src-import/src-import-imported.sass diff --git a/packages/playground/vue-sourcemap/src-import/src-import.css b/playground/vue-sourcemap/src-import/src-import.css similarity index 100% rename from packages/playground/vue-sourcemap/src-import/src-import.css rename to playground/vue-sourcemap/src-import/src-import.css diff --git a/packages/playground/vue-sourcemap/src-import/src-import.sass b/playground/vue-sourcemap/src-import/src-import.sass similarity index 100% rename from packages/playground/vue-sourcemap/src-import/src-import.sass rename to playground/vue-sourcemap/src-import/src-import.sass diff --git a/packages/playground/vue-sourcemap/vite.config.js b/playground/vue-sourcemap/vite.config.ts similarity index 62% rename from packages/playground/vue-sourcemap/vite.config.js rename to playground/vue-sourcemap/vite.config.ts index 2a48cad3cb00d4..dbfa81dbeb1144 100644 --- a/packages/playground/vue-sourcemap/vite.config.js +++ b/playground/vue-sourcemap/vite.config.ts @@ -1,9 +1,7 @@ -const vuePlugin = require('@vitejs/plugin-vue') +import vuePlugin from '@vitejs/plugin-vue' +import { defineConfig } from 'vite' -/** - * @type {import('vite').UserConfig} - */ -module.exports = { +export default defineConfig({ css: { devSourcemap: true, preprocessorOptions: { @@ -16,4 +14,4 @@ module.exports = { build: { sourcemap: true } -} +}) diff --git a/packages/playground/vue/Assets.vue b/playground/vue/Assets.vue similarity index 100% rename from packages/playground/vue/Assets.vue rename to playground/vue/Assets.vue diff --git a/packages/playground/vue/AsyncComponent.vue b/playground/vue/AsyncComponent.vue similarity index 100% rename from packages/playground/vue/AsyncComponent.vue rename to playground/vue/AsyncComponent.vue diff --git a/packages/playground/vue/CssModules.vue b/playground/vue/CssModules.vue similarity index 100% rename from packages/playground/vue/CssModules.vue rename to playground/vue/CssModules.vue diff --git a/packages/playground/vue/CustomBlock.vue b/playground/vue/CustomBlock.vue similarity index 100% rename from packages/playground/vue/CustomBlock.vue rename to playground/vue/CustomBlock.vue diff --git a/packages/playground/vue/CustomBlockPlugin.ts b/playground/vue/CustomBlockPlugin.ts similarity index 100% rename from packages/playground/vue/CustomBlockPlugin.ts rename to playground/vue/CustomBlockPlugin.ts diff --git a/packages/playground/vue/CustomElement.ce.vue b/playground/vue/CustomElement.ce.vue similarity index 100% rename from packages/playground/vue/CustomElement.ce.vue rename to playground/vue/CustomElement.ce.vue diff --git a/packages/playground/vue/Hmr.vue b/playground/vue/Hmr.vue similarity index 100% rename from packages/playground/vue/Hmr.vue rename to playground/vue/Hmr.vue diff --git a/packages/playground/vue/Main.vue b/playground/vue/Main.vue similarity index 96% rename from packages/playground/vue/Main.vue rename to playground/vue/Main.vue index 87319acdf6f736..c5f3d27402fda7 100644 --- a/packages/playground/vue/Main.vue +++ b/playground/vue/Main.vue @@ -15,6 +15,7 @@
this should be red
+ @@ -33,6 +34,7 @@ import CustomBlock from './CustomBlock.vue' import SrcImport from './src-import/SrcImport.vue' import Slotted from './Slotted.vue' import ScanDep from './ScanDep.vue' +import TsImport from './TsImport.vue' import AsyncComponent from './AsyncComponent.vue' import ReactivityTransform from './ReactivityTransform.vue' import SetupImportTemplate from './setup-import-template/SetupImportTemplate.vue' diff --git a/packages/playground/vue/Node.vue b/playground/vue/Node.vue similarity index 100% rename from packages/playground/vue/Node.vue rename to playground/vue/Node.vue diff --git a/packages/playground/vue/PreProcessors.vue b/playground/vue/PreProcessors.vue similarity index 100% rename from packages/playground/vue/PreProcessors.vue rename to playground/vue/PreProcessors.vue diff --git a/packages/playground/vue/ReactivityTransform.vue b/playground/vue/ReactivityTransform.vue similarity index 100% rename from packages/playground/vue/ReactivityTransform.vue rename to playground/vue/ReactivityTransform.vue diff --git a/packages/playground/vue/ScanDep.vue b/playground/vue/ScanDep.vue similarity index 100% rename from packages/playground/vue/ScanDep.vue rename to playground/vue/ScanDep.vue diff --git a/packages/playground/vue/Slotted.vue b/playground/vue/Slotted.vue similarity index 100% rename from packages/playground/vue/Slotted.vue rename to playground/vue/Slotted.vue diff --git a/packages/playground/vue/Syntax.vue b/playground/vue/Syntax.vue similarity index 100% rename from packages/playground/vue/Syntax.vue rename to playground/vue/Syntax.vue diff --git a/playground/vue/TsImport.vue b/playground/vue/TsImport.vue new file mode 100644 index 00000000000000..986c383b2b9f4b --- /dev/null +++ b/playground/vue/TsImport.vue @@ -0,0 +1,8 @@ + + + diff --git a/playground/vue/TsImportFile.ts b/playground/vue/TsImportFile.ts new file mode 100644 index 00000000000000..62761d5733b432 --- /dev/null +++ b/playground/vue/TsImportFile.ts @@ -0,0 +1 @@ +export const foo = 'success' diff --git a/packages/playground/vue/__tests__/vue.spec.ts b/playground/vue/__tests__/vue.spec.ts similarity index 96% rename from packages/playground/vue/__tests__/vue.spec.ts rename to playground/vue/__tests__/vue.spec.ts index 025c05f53e8688..3b6e2cc15555b1 100644 --- a/packages/playground/vue/__tests__/vue.spec.ts +++ b/playground/vue/__tests__/vue.spec.ts @@ -1,4 +1,13 @@ -import { editFile, getBg, getColor, isBuild, untilUpdated } from 'testUtils' +import { + browserLogs, + editFile, + getBg, + getColor, + isBuild, + page, + serverLogs, + untilUpdated +} from '~utils' test('should render', async () => { expect(await page.textContent('h1')).toMatch('Vue SFCs') @@ -14,6 +23,10 @@ test('template/script latest syntax support', async () => { expect(await page.textContent('.syntax')).toBe('baz') }) +test('import ts with .js extension with lang="ts"', async () => { + expect(await page.textContent('.ts-import')).toBe('success') +}) + test('should remove comments in prod', async () => { expect(await page.innerHTML('.comments')).toBe(isBuild ? `` : ``) }) diff --git a/packages/playground/vue/assets/asset.png b/playground/vue/assets/asset.png similarity index 100% rename from packages/playground/vue/assets/asset.png rename to playground/vue/assets/asset.png diff --git a/packages/playground/vue/assets/fragment.svg b/playground/vue/assets/fragment.svg similarity index 100% rename from packages/playground/vue/assets/fragment.svg rename to playground/vue/assets/fragment.svg diff --git a/packages/playground/vue/index.html b/playground/vue/index.html similarity index 100% rename from packages/playground/vue/index.html rename to playground/vue/index.html diff --git a/packages/playground/vue/package.json b/playground/vue/package.json similarity index 77% rename from packages/playground/vue/package.json rename to playground/vue/package.json index f493e9028b6ec3..2c228798e641da 100644 --- a/packages/playground/vue/package.json +++ b/playground/vue/package.json @@ -5,19 +5,19 @@ "scripts": { "dev": "vite", "build": "vite build", - "debug": "node --inspect-brk ../../vite/bin/vite", + "debug": "node --inspect-brk ../../packages/vite/bin/vite", "preview": "vite preview" }, "dependencies": { "lodash-es": "^4.17.21", - "vue": "^3.2.25" + "vue": "^3.2.33" }, "devDependencies": { "@vitejs/plugin-vue": "workspace:*", "js-yaml": "^4.1.0", "less": "^4.1.2", "pug": "^3.0.2", - "sass": "^1.43.4", + "sass": "^1.51.0", "stylus": "^0.55.0" } } diff --git a/packages/playground/vue/public/favicon.ico b/playground/vue/public/favicon.ico similarity index 100% rename from packages/playground/vue/public/favicon.ico rename to playground/vue/public/favicon.ico diff --git a/playground/vue/public/icon.png b/playground/vue/public/icon.png new file mode 100644 index 00000000000000..4388bfdca3d4d7 Binary files /dev/null and b/playground/vue/public/icon.png differ diff --git a/packages/playground/vue/setup-import-template/SetupImportTemplate.vue b/playground/vue/setup-import-template/SetupImportTemplate.vue similarity index 100% rename from packages/playground/vue/setup-import-template/SetupImportTemplate.vue rename to playground/vue/setup-import-template/SetupImportTemplate.vue diff --git a/packages/playground/vue/setup-import-template/template.html b/playground/vue/setup-import-template/template.html similarity index 100% rename from packages/playground/vue/setup-import-template/template.html rename to playground/vue/setup-import-template/template.html diff --git a/packages/playground/vue/src-import/SrcImport.vue b/playground/vue/src-import/SrcImport.vue similarity index 100% rename from packages/playground/vue/src-import/SrcImport.vue rename to playground/vue/src-import/SrcImport.vue diff --git a/playground/vue/src-import/css.module.css b/playground/vue/src-import/css.module.css new file mode 100644 index 00000000000000..09b5c09fb637e2 --- /dev/null +++ b/playground/vue/src-import/css.module.css @@ -0,0 +1,7 @@ +.one { + background: yellow; +} + +.two { + border: solid 1px red; +} diff --git a/packages/playground/vue/src-import/script.ts b/playground/vue/src-import/script.ts similarity index 59% rename from packages/playground/vue/src-import/script.ts rename to playground/vue/src-import/script.ts index 54e6e35db41f46..d20c098a7af289 100644 --- a/packages/playground/vue/src-import/script.ts +++ b/playground/vue/src-import/script.ts @@ -1,11 +1,15 @@ import { defineComponent } from 'vue' import SrcImportStyle from './srcImportStyle.vue' import SrcImportStyle2 from './srcImportStyle2.vue' +import SrcImportModuleStyle from './srcImportModuleStyle.vue' +import SrcImportModuleStyle2 from './srcImportModuleStyle2.vue' export default defineComponent({ components: { SrcImportStyle, - SrcImportStyle2 + SrcImportStyle2, + SrcImportModuleStyle, + SrcImportModuleStyle2 }, setup() { return { diff --git a/playground/vue/src-import/srcImportModuleStyle.vue b/playground/vue/src-import/srcImportModuleStyle.vue new file mode 100644 index 00000000000000..f1e85abb6d2b12 --- /dev/null +++ b/playground/vue/src-import/srcImportModuleStyle.vue @@ -0,0 +1,4 @@ + +