From e20e13696b06e01df5422005304c6f7f75e45cd0 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 13:21:59 -0500 Subject: [PATCH 01/32] release: create-app@1.0.2 --- packages/create-app/CHANGELOG.md | 4 ++++ packages/create-app/package.json | 4 ++-- .../create-app/template-react-ts/package.json | 4 ++-- .../create-app/template-react/package.json | 4 ++-- .../create-app/template-vanilla/package.json | 4 ++-- .../create-app/template-vue-ts/package.json | 4 ++-- packages/create-app/template-vue/package.json | 6 +++--- packages/create-app/updateVersions.js | 18 ++++++++++++++++++ 8 files changed, 35 insertions(+), 13 deletions(-) create mode 100644 packages/create-app/updateVersions.js diff --git a/packages/create-app/CHANGELOG.md b/packages/create-app/CHANGELOG.md index 9140b2115b3889..f6b696208ff4ef 100644 --- a/packages/create-app/CHANGELOG.md +++ b/packages/create-app/CHANGELOG.md @@ -1,3 +1,7 @@ +## [1.0.2](https://github.com/vitejs/vite/compare/create-app@1.0.1...create-app@1.0.2) (2021-01-02) + + + ## [1.0.1](https://github.com/vitejs/vite/compare/create-app@1.0.0...create-app@1.0.1) (2021-01-02) diff --git a/packages/create-app/package.json b/packages/create-app/package.json index 538e5694afd12f..59a8b606b8d059 100644 --- a/packages/create-app/package.json +++ b/packages/create-app/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/create-app", - "version": "1.0.1", + "version": "1.0.2", "license": "MIT", "author": "Evan You", "bin": { @@ -14,7 +14,7 @@ "main": "index.js", "scripts": { "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . --lerna-package create-app", - "release": "node ../../scripts/release.js --skipBuild" + "release": "node updateVersions && node ../../scripts/release.js --skipBuild" }, "engines": { "node": ">=12.0.0" diff --git a/packages/create-app/template-react-ts/package.json b/packages/create-app/template-react-ts/package.json index 14cb0e7be9f3db..a100cee4f54810 100644 --- a/packages/create-app/template-react-ts/package.json +++ b/packages/create-app/template-react-ts/package.json @@ -14,6 +14,6 @@ "@types/react-dom": "^17.0.0", "@vitejs/plugin-react-refresh": "^1.1.0", "typescript": "^4.1.2", - "vite": "^2.0.0-beta.1" + "vite": "^2.0.0-beta.2" } -} +} \ No newline at end of file diff --git a/packages/create-app/template-react/package.json b/packages/create-app/template-react/package.json index a091e5e73e2ad7..6a0c56265feedf 100644 --- a/packages/create-app/template-react/package.json +++ b/packages/create-app/template-react/package.json @@ -11,6 +11,6 @@ }, "devDependencies": { "@vitejs/plugin-react-refresh": "^1.1.0", - "vite": "^2.0.0-beta.1" + "vite": "^2.0.0-beta.2" } -} +} \ No newline at end of file diff --git a/packages/create-app/template-vanilla/package.json b/packages/create-app/template-vanilla/package.json index c901d59695e877..e9b6d6a0f4599f 100644 --- a/packages/create-app/template-vanilla/package.json +++ b/packages/create-app/template-vanilla/package.json @@ -6,6 +6,6 @@ "build": "vite build" }, "devDependencies": { - "vite": "^2.0.0-beta.1" + "vite": "^2.0.0-beta.2" } -} +} \ No newline at end of file diff --git a/packages/create-app/template-vue-ts/package.json b/packages/create-app/template-vue-ts/package.json index 81bfc03e95a47c..410dd63243e16a 100644 --- a/packages/create-app/template-vue-ts/package.json +++ b/packages/create-app/template-vue-ts/package.json @@ -9,11 +9,11 @@ "vue": "^3.0.5" }, "devDependencies": { - "@vitejs/plugin-vue": "^1.0.2", + "@vitejs/plugin-vue": "^1.0.3", "@vue/compiler-sfc": "^3.0.5", "@vuedx/typecheck": "^0.4.1", "@vuedx/typescript-plugin-vue": "^0.4.1", "typescript": "^4.1.3", - "vite": "^2.0.0-beta.1" + "vite": "^2.0.0-beta.2" } } \ No newline at end of file diff --git a/packages/create-app/template-vue/package.json b/packages/create-app/template-vue/package.json index 10fae9dd29acd3..cd23f91498ab6c 100644 --- a/packages/create-app/template-vue/package.json +++ b/packages/create-app/template-vue/package.json @@ -9,8 +9,8 @@ "vue": "^3.0.5" }, "devDependencies": { - "@vitejs/plugin-vue": "^1.0.2", + "@vitejs/plugin-vue": "^1.0.3", "@vue/compiler-sfc": "^3.0.5", - "vite": "^2.0.0-beta.1" + "vite": "^2.0.0-beta.2" } -} +} \ No newline at end of file diff --git a/packages/create-app/updateVersions.js b/packages/create-app/updateVersions.js new file mode 100644 index 00000000000000..96ab51fbc10a0a --- /dev/null +++ b/packages/create-app/updateVersions.js @@ -0,0 +1,18 @@ +const fs = require('fs') +const path = require('path') + +;(async () => { + const templates = fs + .readdirSync(__dirname) + .filter((d) => d.startsWith('template-')) + for (const t of templates) { + const pkgPath = path.join(__dirname, t, `package.json`) + const pkg = require(pkgPath) + pkg.devDependencies.vite = `^` + require('../vite/package.json').version + if (t.startsWith('template-vue')) { + pkg.devDependencies['@vitejs/plugin-vue'] = + `^` + require('../plugin-vue/package.json').version + } + fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)) + } +})() From 05f242b215fe7348d4a14d744e9825e14f5cd4d7 Mon Sep 17 00:00:00 2001 From: HG Date: Sat, 2 Jan 2021 18:23:03 +0000 Subject: [PATCH 02/32] chore: readme typo [skip ci] --- packages/create-app/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/create-app/README.md b/packages/create-app/README.md index 23aa31b9fe4367..37fa3c9fbd5cbd 100644 --- a/packages/create-app/README.md +++ b/packages/create-app/README.md @@ -2,7 +2,7 @@ ## Scaffolding Your First Vite Project -> **Comaptibility Note:** +> **Compatibility Note:** > Vite requires [Node.js](https://nodejs.org/en/) version >=12.0.0. With NPM: From 8f937a2e9af77f3b7de00aac07723642c0978e48 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 13:29:38 -0500 Subject: [PATCH 03/32] chore: bump vitepress --- package.json | 2 +- yarn.lock | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index e6d461b585baa6..eed6c257448a86 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "slash": "^3.0.0", "ts-jest": "^26.4.4", "typescript": "^4.1.2", - "vitepress": "^0.10.4", + "vitepress": "^0.10.5", "yorkie": "^2.0.0" }, "gitHooks": { diff --git a/yarn.lock b/yarn.lock index 73805049280439..c7662858d2fee8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7466,14 +7466,14 @@ verror@1.10.0: core-util-is "1.0.2" extsprintf "^1.2.0" -vitepress@^0.10.4: - version "0.10.4" - resolved "https://registry.yarnpkg.com/vitepress/-/vitepress-0.10.4.tgz#65b5a6be2503ea492fd79082d576bd73725abc25" - integrity sha512-VvSANRPGNsUlsieruktRacdtG1P/jsQdMcY6NEs/lc7k/YwW1np7wLSQChk0DPgUdEnLDu/pOXQq+iTuOarTdA== +vitepress@^0.10.5: + version "0.10.5" + resolved "https://registry.yarnpkg.com/vitepress/-/vitepress-0.10.5.tgz#56aa2085dced64b157dbef17a092834c829e3bcb" + integrity sha512-dMhcEmTbRZ0sfQ6nYx4kivpg9meYL+HoXQ7hkqKH0B9qFMwTMW3jC7QDX4omc8fF14TWxOnywNVuBvkN23DN0g== dependencies: "@docsearch/css" "^1.0.0-alpha.28" "@docsearch/js" "^1.0.0-alpha.28" - "@vitejs/plugin-vue" "^1.0.2" + "@vitejs/plugin-vue" "^1.0.3" "@vue/compiler-sfc" "^3.0.5" "@vue/server-renderer" "^3.0.5" chalk "^4.1.0" @@ -7496,7 +7496,7 @@ vitepress@^0.10.4: prismjs "^1.20.0" sirv "^1.0.10" slash "^3.0.0" - vite "^2.0.0-alpha.5" + vite "^2.0.0-beta.2" vue "^3.0.5" void-elements@^3.1.0: From d135949013ea0e572fe0a7b22bb9306644036c08 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 13:34:11 -0500 Subject: [PATCH 04/32] fix: fix yarn create compat --- packages/create-app/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/create-app/package.json b/packages/create-app/package.json index 59a8b606b8d059..3c4bbce24c9bc3 100644 --- a/packages/create-app/package.json +++ b/packages/create-app/package.json @@ -4,7 +4,7 @@ "license": "MIT", "author": "Evan You", "bin": { - "create-vite-app": "index.js", + "create-app": "index.js", "cva": "index.js" }, "files": [ From f49cfa9693b8f890d96f36ec7ce8feec53d8b906 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 13:34:22 -0500 Subject: [PATCH 05/32] release: create-app@1.0.3 --- packages/create-app/CHANGELOG.md | 9 +++++++++ packages/create-app/package.json | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/create-app/CHANGELOG.md b/packages/create-app/CHANGELOG.md index f6b696208ff4ef..cf404eaa46f700 100644 --- a/packages/create-app/CHANGELOG.md +++ b/packages/create-app/CHANGELOG.md @@ -1,3 +1,12 @@ +## [1.0.3](https://github.com/vitejs/vite/compare/create-app@1.0.2...create-app@1.0.3) (2021-01-02) + + +### Bug Fixes + +* fix yarn create compat ([d135949](https://github.com/vitejs/vite/commit/d135949013ea0e572fe0a7b22bb9306644036c08)) + + + ## [1.0.2](https://github.com/vitejs/vite/compare/create-app@1.0.1...create-app@1.0.2) (2021-01-02) diff --git a/packages/create-app/package.json b/packages/create-app/package.json index 3c4bbce24c9bc3..76a2eaf19015d1 100644 --- a/packages/create-app/package.json +++ b/packages/create-app/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/create-app", - "version": "1.0.2", + "version": "1.0.3", "license": "MIT", "author": "Evan You", "bin": { From 81e5b6132486831953389f33bd52beb04ec649a6 Mon Sep 17 00:00:00 2001 From: csr632 <632882184@qq.com> Date: Sun, 3 Jan 2021 03:23:15 +0800 Subject: [PATCH 06/32] docs: fix anchor link (#1301) --- docs/guide/env-and-mode.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index 3e6f3228b32399..0bffee0ba6fc12 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -4,7 +4,7 @@ Vite exposes env variables on the special **`import.meta.env`** object. Some built-in variables are available in all cases: -- **`import.meta.env.MODE`**: {string} the [mode](#mode) the app is running in. +- **`import.meta.env.MODE`**: {string} the [mode](#modes) the app is running in. - **`import.meta.env.BASE_URL`**: {string} the base url the app is being served from. In development, this is always `/`. In production, this is determined by the [`build.base` config option](/config/#build-base). From 6ce6d5c2908c20b8308725a5f91f5a618aa09d8a Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 14:38:02 -0500 Subject: [PATCH 07/32] fix(resolve): prioritize module + avoid mutating path when browser field is present but no match is found fix #1299 --- packages/vite/src/node/plugins/resolve.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 847913f60b85b2..023803dab90b5e 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -20,7 +20,7 @@ import { createFilter } from '@rollup/pluginutils' import { PartialResolvedId } from 'rollup' import isBuiltin from 'isbuiltin' -const mainFields = ['browser', 'module', 'jsnext', 'jsnext:main', 'main'] +const mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main'] const isDebug = process.env.DEBUG const debug = createDebugger('vite:resolve-details', { @@ -432,9 +432,9 @@ function mapWithBrowserField( ([from]) => normalize(from) === normalized ) if (!foundEntry) { - return normalized + return relativePathInPkgDir } - return normalize(foundEntry[1]) + return foundEntry[1] } function normalize(file: string) { From 9d0a8e74d1553c8c9108caeaf0c22cd938a502c7 Mon Sep 17 00:00:00 2001 From: Alex Kozack Date: Sat, 2 Jan 2021 21:43:16 +0200 Subject: [PATCH 08/32] feat: expose `loadEnv` in public api (#1300) --- packages/vite/src/node/config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 6c1b0504dad075..e48cdceecf7d91 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -476,7 +476,7 @@ async function loadConfigFromBundledFile( return config } -function loadEnv(mode: string, root: string, prefix = 'VITE_') { +export function loadEnv(mode: string, root: string, prefix = 'VITE_') { if (mode === 'local') { throw new Error( `"local" cannot be used as a mode name because it conflicts with ` + From 56bcb0c475a5dff31527cad6dcd7c61fde424f5e Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Sun, 3 Jan 2021 09:09:22 +0900 Subject: [PATCH 09/32] feat(plugin-vue): export vue query parse API (#1303) --- packages/plugin-vue/src/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/plugin-vue/src/index.ts b/packages/plugin-vue/src/index.ts index 99c3fe6d56ba83..c0984ba6c545de 100644 --- a/packages/plugin-vue/src/index.ts +++ b/packages/plugin-vue/src/index.ts @@ -31,6 +31,8 @@ declare module '@vue/compiler-sfc' { } } +export { parseVueRequest, VueQuery } from './utils/query' + export interface Options { include?: string | RegExp | (string | RegExp)[] exclude?: string | RegExp | (string | RegExp)[] From b665b92323521475a568f8c5204a83c0e80a6b75 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Sat, 2 Jan 2021 19:15:02 -0500 Subject: [PATCH 10/32] fix: keep `this` defined in `configureServer` hook (#1304) --- packages/vite/src/node/server/index.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index 67b289f2ee6a73..c777706303934a 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -266,8 +266,9 @@ export async function createServer( // apply server configuration hooks from plugins const postHooks: ((() => void) | void)[] = [] for (const plugin of plugins) { - const hook = plugin.configureServer - hook && postHooks.push(await hook(server)) + if (plugin.configureServer) { + postHooks.push(await plugin.configureServer(server)) + } } // Internal middlewares ------------------------------------------------------ From 7858e629273269ca2aedf9891d560521a4bd0c8d Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 22:35:24 -0500 Subject: [PATCH 11/32] feat: dedupe option close #1302 --- docs/config/index.md | 7 ++++++ .../foo.js | 0 .../optimize-deps-linked-include/index.js | 7 ++++++ .../optimize-deps-linked-include/package.json | 8 ++++++ .../__tests__/optimize-deps.spec.ts | 6 +++++ packages/playground/optimize-deps/dedupe.js | 22 ++++++++++++++++ packages/playground/optimize-deps/index.html | 6 ++++- .../linked-force-include/index.js | 1 - .../linked-force-include/package.json | 5 ---- .../playground/optimize-deps/package.json | 2 +- .../playground/optimize-deps/vite.config.js | 4 ++- packages/vite/src/node/config.ts | 15 +++++++---- packages/vite/src/node/optimizer/index.ts | 7 +++++- packages/vite/src/node/plugins/index.ts | 7 +++++- packages/vite/src/node/plugins/resolve.ts | 25 ++++++++++++++++--- yarn.lock | 12 ++++++--- 16 files changed, 110 insertions(+), 24 deletions(-) rename packages/playground/{optimize-deps/linked-force-include => optimize-deps-linked-include}/foo.js (100%) create mode 100644 packages/playground/optimize-deps-linked-include/index.js create mode 100644 packages/playground/optimize-deps-linked-include/package.json create mode 100644 packages/playground/optimize-deps/dedupe.js delete mode 100644 packages/playground/optimize-deps/linked-force-include/index.js delete mode 100644 packages/playground/optimize-deps/linked-force-include/package.json diff --git a/docs/config/index.md b/docs/config/index.md index 03245ce9e0f4fb..b6dd42168773bc 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -170,6 +170,13 @@ export default ({ command, mode }) => { Vite will not be able to know that the file needs to be transformed to JavaScript (instead of being served directly as a static file). `transformInclude` allows you to explicitly declare the file type to always be transformed and served as JavaScript. +### dedupe + +- **Type:** `string[]` + + If you have duplicated copies of the same depdendency in your app (likely due to hoisting or linked packages in monorepos), use this option to force Vite to always resolve listed dependencies to the same copy (from + project root). + ### logLevel - **Type:** `'info' | 'warn' | 'error' | 'silent'` diff --git a/packages/playground/optimize-deps/linked-force-include/foo.js b/packages/playground/optimize-deps-linked-include/foo.js similarity index 100% rename from packages/playground/optimize-deps/linked-force-include/foo.js rename to packages/playground/optimize-deps-linked-include/foo.js diff --git a/packages/playground/optimize-deps-linked-include/index.js b/packages/playground/optimize-deps-linked-include/index.js new file mode 100644 index 00000000000000..74c1e295715f63 --- /dev/null +++ b/packages/playground/optimize-deps-linked-include/index.js @@ -0,0 +1,7 @@ +export { msg } from './foo.js' + +import { useState } from 'react' + +export function useCount() { + return useState(0) +} diff --git a/packages/playground/optimize-deps-linked-include/package.json b/packages/playground/optimize-deps-linked-include/package.json new file mode 100644 index 00000000000000..79a03c3a91fc73 --- /dev/null +++ b/packages/playground/optimize-deps-linked-include/package.json @@ -0,0 +1,8 @@ +{ + "name": "optimize-deps-linked-include", + "version": "0.0.0", + "main": "index.js", + "dependencies": { + "react": "17.0.0" + } +} diff --git a/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts b/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts index 3055dad64c9a15..f7616fb9d6be71 100644 --- a/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts +++ b/packages/playground/optimize-deps/__tests__/optimize-deps.spec.ts @@ -10,6 +10,12 @@ test('dynamic imports from cjs dep (react)', async () => { expect(await page.textContent('.cjs-dynamic button')).toBe('count is 1') }) +test('dedupe', async () => { + expect(await page.textContent('.dedupe button')).toBe('count is 0') + await page.click('.dedupe button') + expect(await page.textContent('.dedupe button')).toBe('count is 1') +}) + test('cjs borwser field (axios)', async () => { expect(await page.textContent('.cjs-browser-field')).toBe('pong') }) diff --git a/packages/playground/optimize-deps/dedupe.js b/packages/playground/optimize-deps/dedupe.js new file mode 100644 index 00000000000000..b1cf69a959330a --- /dev/null +++ b/packages/playground/optimize-deps/dedupe.js @@ -0,0 +1,22 @@ +// test importing both default and named exports from a CommonJS module +// React is the ultimate test of this because its dynamic exports assignments +// are not statically detectable by @rollup/plugin-commonjs. +import React, { useState } from 'react' +import ReactDOM from 'react-dom' +import { useCount } from 'optimize-deps-linked-include' + +function App() { + const [count, setCount] = useCount() + + return React.createElement( + 'button', + { + onClick() { + setCount(count + 1) + } + }, + `count is ${count}` + ) +} + +ReactDOM.render(React.createElement(App), document.querySelector('.dedupe')) diff --git a/packages/playground/optimize-deps/index.html b/packages/playground/optimize-deps/index.html index 892d90e068fd27..d79167fa82bf80 100644 --- a/packages/playground/optimize-deps/index.html +++ b/packages/playground/optimize-deps/index.html @@ -8,6 +8,10 @@

CommonJS dynamic import (react)

+

Dedupe (dep in linked & optimized package)

+
+ +

CommonJS w/ browser field mapping (axios)

This should show ping:
@@ -27,6 +31,6 @@

Optimizing force included dep even when it's linked

import { camelCase } from 'optimize-deps-linked' document.querySelector('.deps-linked').textContent = camelCase('foo-bar-baz') -import { msg } from 'linked-force-include' +import { msg } from 'optimize-deps-linked-include' document.querySelector('.force-include').textContent = msg diff --git a/packages/playground/optimize-deps/linked-force-include/index.js b/packages/playground/optimize-deps/linked-force-include/index.js deleted file mode 100644 index a81424667cfbcd..00000000000000 --- a/packages/playground/optimize-deps/linked-force-include/index.js +++ /dev/null @@ -1 +0,0 @@ -export { msg } from './foo.js' diff --git a/packages/playground/optimize-deps/linked-force-include/package.json b/packages/playground/optimize-deps/linked-force-include/package.json deleted file mode 100644 index 4589ae5012c7d0..00000000000000 --- a/packages/playground/optimize-deps/linked-force-include/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "linked-force-include", - "version": "0.0.0", - "main": "index.js" -} \ No newline at end of file diff --git a/packages/playground/optimize-deps/package.json b/packages/playground/optimize-deps/package.json index 67fdbb6f002606..7b5e9c8fdb39be 100644 --- a/packages/playground/optimize-deps/package.json +++ b/packages/playground/optimize-deps/package.json @@ -13,6 +13,6 @@ "react-dom": "^17.0.1", "resolve-linked": "0.0.0", "optimize-deps-linked": "0.0.0", - "linked-force-include": "link:./linked-force-include" + "optimize-deps-linked-include": "0.0.0" } } diff --git a/packages/playground/optimize-deps/vite.config.js b/packages/playground/optimize-deps/vite.config.js index 90850a68f8637f..267e0ff2be1995 100644 --- a/packages/playground/optimize-deps/vite.config.js +++ b/packages/playground/optimize-deps/vite.config.js @@ -2,8 +2,10 @@ * @type {import('vite').UserConfig} */ module.exports = { + dedupe: ['react'], + optimizeDeps: { - include: ['linked-force-include'] + include: ['optimize-deps-linked-include'] }, build: { diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index e48cdceecf7d91..8c6d13405b9a13 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -92,6 +92,11 @@ export interface UserConfig { * Dep optimization options */ optimizeDeps?: DepOptimizationOptions + /** + * Force Vite to always resolve listed dependencies to the same copy (from + * project root). + */ + dedupe?: string[] /** * Log level. * Default: 'info' @@ -416,11 +421,11 @@ async function loadConfigFromFile( plugins: [ // use esbuild + node-resolve to support .ts files esbuildPlugin({ target: 'es2019' }), - resolvePlugin( - path.dirname(resolvedPath), - true /* isBuild */, - false /* disallow src code only resolves */ - ) + resolvePlugin({ + root: path.dirname(resolvedPath), + isBuild: true, + asSrc: false + }) ] }) diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 4f3623012a7efd..84c71c1154c778 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -180,7 +180,12 @@ export async function optimizeDeps( aliasPlugin({ entries: config.alias }), depAssetExternalPlugin(config), // TODO user pre plugins? - resolvePlugin(config.root, true /* isBuild */, false /* asSrc */), + resolvePlugin({ + root: config.root, + dedupe: config.dedupe, + isBuild: true, + asSrc: false + }), jsonPlugin({ preferConst: true, namedExports: true diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index 858a85974f3f98..8f7bae79431697 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -27,7 +27,12 @@ export async function resolvePlugins( return [ aliasPlugin({ entries: config.alias }), ...prePlugins, - resolvePlugin(config.root, isBuild, true), + resolvePlugin({ + root: config.root, + dedupe: config.dedupe, + isBuild, + asSrc: true + }), htmlPlugin(), cssPlugin(config), config.esbuild !== false ? esbuildPlugin(config.esbuild) : null, diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 023803dab90b5e..b40513a753b712 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -27,16 +27,24 @@ const debug = createDebugger('vite:resolve-details', { onlyWhenFocused: true }) -export function resolvePlugin( - root: string, - isBuild: boolean, +interface ResolveOptions { + root: string + isBuild: boolean /** * src code mode also attempts the following: * - resolving /xxx as URLs * - resolving bare imports from optimized deps */ asSrc: boolean -): Plugin { + dedupe?: string[] +} + +export function resolvePlugin({ + root, + isBuild, + asSrc, + dedupe +}: ResolveOptions): Plugin { let server: ViteDevServer return { @@ -124,6 +132,8 @@ export function resolvePlugin( id, importer ? path.dirname(importer) : root, isBuild, + dedupe, + root, server )) ) { @@ -180,10 +190,17 @@ export function tryNodeResolve( id: string, basedir: string, isBuild = true, + dedupe?: string[], + dedupeRoot?: string, server?: ViteDevServer ): PartialResolvedId | undefined { const deepMatch = id.match(deepImportRE) const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id + + if (dedupe && dedupeRoot && dedupe.includes(pkgId)) { + basedir = dedupeRoot + } + const pkg = resolvePackageData(pkgId, basedir) if (!pkg) { diff --git a/yarn.lock b/yarn.lock index c7662858d2fee8..ff65ccb6850382 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4628,10 +4628,6 @@ lines-and-columns@^1.1.6: resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= -"linked-force-include@link:./packages/playground/optimize-deps/linked-force-include": - version "0.0.0" - uid "" - linkify-it@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf" @@ -6102,6 +6098,14 @@ react-refresh@^0.9.0: resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.9.0.tgz#71863337adc3e5c2f8a6bfddd12ae3bfe32aafbf" integrity sha512-Gvzk7OZpiqKSkxsQvO/mbTN1poglhmAV7gR/DdIrRrSMXraRQQlfikRJOr3Nb9GTMPC5kof948Zy6jJZIFtDvQ== +react@17.0.0: + version "17.0.0" + resolved "https://registry.yarnpkg.com/react/-/react-17.0.0.tgz#ad96d5fa1a33bb9b06d0cc52672f7992d84aa662" + integrity sha512-rG9bqS3LMuetoSUKHN8G3fMNuQOePKDThK6+2yXFWtoeTDLVNh/QCaxT+Jr+rNf4lwNXpx+atdn3Aa0oi8/6eQ== + dependencies: + loose-envify "^1.1.0" + object-assign "^4.1.1" + react@^17.0.1: version "17.0.1" resolved "https://registry.yarnpkg.com/react/-/react-17.0.1.tgz#6e0600416bd57574e3f86d92edba3d9008726127" From ec2bf6cc8fb654ac0d70966935ac877651359f6e Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 22:38:07 -0500 Subject: [PATCH 12/32] chore: test comments [skip ci] --- packages/playground/optimize-deps/dedupe.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/playground/optimize-deps/dedupe.js b/packages/playground/optimize-deps/dedupe.js index b1cf69a959330a..3f7f6e656e33e7 100644 --- a/packages/playground/optimize-deps/dedupe.js +++ b/packages/playground/optimize-deps/dedupe.js @@ -1,8 +1,9 @@ -// test importing both default and named exports from a CommonJS module -// React is the ultimate test of this because its dynamic exports assignments -// are not statically detectable by @rollup/plugin-commonjs. -import React, { useState } from 'react' +import React from 'react' import ReactDOM from 'react-dom' + +// #1302: The linked package has a different version of React in its deps +// and is itself optimized. Without `dedupe`, the linked package is optimized +// with a separate copy of React included, and results in runtime errors. import { useCount } from 'optimize-deps-linked-include' function App() { From 38b9613832d1af569ca5aba4226895f0bd7897a0 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Sat, 2 Jan 2021 22:39:17 -0500 Subject: [PATCH 13/32] feat: export `resolvePackageData` and `resolvePackageEntry` helpers (#1307) * feat: export `resolvePackageData` and `resolvePackageEntry` helpers These functions can be useful to plugins. - `resolvePackageData` provides cache reuse - `resolvePackageEntry` is complicated enough to be burdensome to reimplement for a plugin to achieve the same behavior * feat: export `PackageData` type --- packages/vite/src/node/index.ts | 2 ++ packages/vite/src/node/plugins/resolve.ts | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts index 37008fd2c4cdb2..910b23f9e0110c 100644 --- a/packages/vite/src/node/index.ts +++ b/packages/vite/src/node/index.ts @@ -4,6 +4,7 @@ export * from './optimizer' export * from './config' export { send } from './server/send' export { createLogger } from './logger' +export { resolvePackageData, resolvePackageEntry } from './plugins/resolve' // additional types export type { Plugin } from './plugin' @@ -23,6 +24,7 @@ export type { } from './plugins/html' export type { CSSOptions, CSSModulesOptions } from './plugins/css' export type { EsbuildTransformResult } from './plugins/esbuild' +export type { PackageData } from './plugins/resolve' export type { WebSocketServer } from './server/ws' export type { PluginContainer } from './server/pluginContainer' export type { ModuleGraph, ModuleNode } from './server/moduleGraph' diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index b40513a753b712..a2d54e522ef31d 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -272,7 +272,7 @@ function tryOptimizedResolve( } } -interface PackageData { +export interface PackageData { dir: string hasSideEffects: (id: string) => boolean data: { @@ -285,7 +285,7 @@ interface PackageData { const packageCache = new Map() -function resolvePackageData( +export function resolvePackageData( id: string, basedir: string ): PackageData | undefined { From f52db5898dfb1eecb4b3427a73ffd7ecd2ac15d6 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 22:50:28 -0500 Subject: [PATCH 14/32] fix: decode incoming URL fixes cases where user paths contains chars that are encoded when used in URLs. fix #1308 --- packages/vite/src/node/server/middlewares/transform.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index b4c5a0d48326a5..e51989a65b060a 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -31,7 +31,6 @@ export function transformMiddleware( } = server return async (req, res, next) => { - let url = removeTimestampQuery(req.url!) if ( req.method !== 'GET' || req.headers.accept?.includes('text/html') || @@ -40,6 +39,7 @@ export function transformMiddleware( return next() } + let url = decodeURI(removeTimestampQuery(req.url!)) const withoutQuery = cleanUrl(url) try { From b57d74c2b72498aee251ed7ed45ff046a98d5499 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 23:00:29 -0500 Subject: [PATCH 15/32] fix(build): fix import-fresh shim fix #1306 --- packages/vite/rollup.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/rollup.config.js b/packages/vite/rollup.config.js index 43e152de610581..b5d9f553f8b24e 100644 --- a/packages/vite/rollup.config.js +++ b/packages/vite/rollup.config.js @@ -118,7 +118,7 @@ const nodeConfig = { replacement: `eval('require')('sugarss')` }, 'import-fresh/index.js': { - pattern: /require\(filePath\)/g, + src: `require(filePath)`, replacement: `eval('require')(filePath)` }, 'import-from/index.js': { From 20ccf3d1a6e2d73b824cb8047d7ccf616177392a Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 2 Jan 2021 23:32:14 -0500 Subject: [PATCH 16/32] release: v2.0.0-beta.3 --- packages/vite/CHANGELOG.md | 19 +++++++++++++++++++ packages/vite/package.json | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index d609119cc9f6f6..db95bce852a88e 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,22 @@ +# [2.0.0-beta.3](https://github.com/vitejs/vite/compare/v2.0.0-beta.2...v2.0.0-beta.3) (2021-01-03) + + +### Bug Fixes + +* **build:** fix import-fresh shim ([b57d74c](https://github.com/vitejs/vite/commit/b57d74c2b72498aee251ed7ed45ff046a98d5499)), closes [#1306](https://github.com/vitejs/vite/issues/1306) +* decode incoming URL ([f52db58](https://github.com/vitejs/vite/commit/f52db5898dfb1eecb4b3427a73ffd7ecd2ac15d6)), closes [#1308](https://github.com/vitejs/vite/issues/1308) +* keep `this` defined in `configureServer` hook ([#1304](https://github.com/vitejs/vite/issues/1304)) ([b665b92](https://github.com/vitejs/vite/commit/b665b92323521475a568f8c5204a83c0e80a6b75)) +* **resolve:** prioritize module + avoid mutating path when ([6ce6d5c](https://github.com/vitejs/vite/commit/6ce6d5c2908c20b8308725a5f91f5a618aa09d8a)), closes [#1299](https://github.com/vitejs/vite/issues/1299) + + +### Features + +* dedupe option ([7858e62](https://github.com/vitejs/vite/commit/7858e629273269ca2aedf9891d560521a4bd0c8d)), closes [#1302](https://github.com/vitejs/vite/issues/1302) +* export `resolvePackageData` and `resolvePackageEntry` helpers ([#1307](https://github.com/vitejs/vite/issues/1307)) ([38b9613](https://github.com/vitejs/vite/commit/38b9613832d1af569ca5aba4226895f0bd7897a0)) +* expose `loadEnv` in public api ([#1300](https://github.com/vitejs/vite/issues/1300)) ([9d0a8e7](https://github.com/vitejs/vite/commit/9d0a8e74d1553c8c9108caeaf0c22cd938a502c7)) + + + # [2.0.0-beta.2](https://github.com/vitejs/vite/compare/v2.0.0-beta.1...v2.0.0-beta.2) (2021-01-02) diff --git a/packages/vite/package.json b/packages/vite/package.json index ec7c36a625fc6a..eace98a71b1e93 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.0.0-beta.2", + "version": "2.0.0-beta.3", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From 95dd9d1096fafe6a5942576a7d31263ab39adcf2 Mon Sep 17 00:00:00 2001 From: csr632 <632882184@qq.com> Date: Sun, 3 Jan 2021 16:28:03 +0800 Subject: [PATCH 17/32] chore: fix comment (#1314) --- packages/vite/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/package.json b/packages/vite/package.json index eace98a71b1e93..e4d0feec7ee8cc 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -41,7 +41,7 @@ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .", "release": "node ../../scripts/release.js" }, - "//": "READ .github/maintenance.md to understand what to put under deps vs. devDeps!", + "//": "READ .github/contributing.md to understand what to put under deps vs. devDeps!", "dependencies": { "esbuild": "^0.8.26", "postcss": "^8.2.1", From 06663a7e7825bedd61593d299f00110f6ac40916 Mon Sep 17 00:00:00 2001 From: CHOYSEN <582511362@qq.com> Date: Sun, 3 Jan 2021 16:30:43 +0800 Subject: [PATCH 18/32] fix(dev): display localetime correctly (#1310) --- packages/vite/src/node/logger.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/logger.ts b/packages/vite/src/node/logger.ts index b34b81144f7c7e..262a491b3b8791 100644 --- a/packages/vite/src/node/logger.ts +++ b/packages/vite/src/node/logger.ts @@ -50,7 +50,7 @@ export function createLogger(level: LogLevel = 'info'): Logger { ? chalk.yellow.bold(`[vite]`) : chalk.red.bold(`[vite]`) return `${chalk.dim( - new Date().toLocaleString().split(', ')[1] + new Date().toLocaleTimeString() )} ${tag} ${msg}` } else { return msg From b74c3e2543855c1a1a0d9fc3f2088ab9a0eb3510 Mon Sep 17 00:00:00 2001 From: Matias Capeletto Date: Sun, 3 Jan 2021 22:26:02 +0100 Subject: [PATCH 19/32] chore(create-app): vue package name (#1319) [skip ci] --- packages/create-app/template-vue/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/create-app/template-vue/package.json b/packages/create-app/template-vue/package.json index cd23f91498ab6c..f0ee82416e903c 100644 --- a/packages/create-app/template-vue/package.json +++ b/packages/create-app/template-vue/package.json @@ -1,5 +1,5 @@ { - "name": "vite-starter", + "name": "vite-vue-starter", "version": "0.0.0", "scripts": { "dev": "vite", From 37d1a5de019cfd5db397f5c8e0365222950c1dff Mon Sep 17 00:00:00 2001 From: Matias Capeletto Date: Sun, 3 Jan 2021 22:30:43 +0100 Subject: [PATCH 20/32] feat: export normalizePath helper (#1313) --- packages/vite/src/node/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts index 910b23f9e0110c..898742a3926eb6 100644 --- a/packages/vite/src/node/index.ts +++ b/packages/vite/src/node/index.ts @@ -5,6 +5,7 @@ export * from './config' export { send } from './server/send' export { createLogger } from './logger' export { resolvePackageData, resolvePackageEntry } from './plugins/resolve' +export { normalizePath } from './utils' // additional types export type { Plugin } from './plugin' From 331484c2600e96543aa8007b4940d023cb5cc19f Mon Sep 17 00:00:00 2001 From: underfin Date: Mon, 4 Jan 2021 05:32:03 +0800 Subject: [PATCH 21/32] fix(plugin-vue): mark SFC compiler options as `Partial` (#1316) --- packages/plugin-vue/src/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/plugin-vue/src/index.ts b/packages/plugin-vue/src/index.ts index c0984ba6c545de..d7155d525d86e9 100644 --- a/packages/plugin-vue/src/index.ts +++ b/packages/plugin-vue/src/index.ts @@ -41,9 +41,9 @@ export interface Options { isProduction?: boolean // options to pass on to @vue/compiler-sfc - script?: SFCScriptCompileOptions - template?: SFCTemplateCompileOptions - style?: SFCStyleCompileOptions + script?: Partial + template?: Partial + style?: Partial } export interface ResolvedOptions extends Options { From 1da12baf00ab8e7c3366f9c0e088c09cce903934 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Sun, 3 Jan 2021 16:34:11 -0500 Subject: [PATCH 22/32] fix: sourcemap path mangled by browser (#1326) Closes #1323 --- .../vite/src/node/server/middlewares/transform.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index e51989a65b060a..3c1e844b227e70 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -15,7 +15,12 @@ import { send } from '../send' import { transformRequest } from '../transformRequest' import { isHTMLProxy } from '../../plugins/html' import chalk from 'chalk' -import { DEP_CACHE_DIR, DEP_VERSION_RE, VALID_ID_PREFIX } from '../../constants' +import { + DEP_CACHE_DIR, + DEP_VERSION_RE, + FS_PREFIX, + VALID_ID_PREFIX +} from '../../constants' const debugCache = createDebugger('vite:cache') const isDebug = !!process.env.DEBUG @@ -46,6 +51,10 @@ export function transformMiddleware( const isSourceMap = withoutQuery.endsWith('.map') // since we generate source map references, handle those requests here if (isSourceMap) { + // #1323 - browser may remove // when fetching source maps + if (url.startsWith(FS_PREFIX)) { + url = FS_PREFIX + url.split(FS_PREFIX)[1].replace(/^\/?/, '/') + } const originalUrl = url.replace(/\.map($|\?)/, '$1') const map = (await moduleGraph.getModuleByUrl(originalUrl)) ?.transformResult?.map From 1f89b0e704d4315246836d2cd7faf3cdcdf89dd9 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Sun, 3 Jan 2021 16:37:27 -0500 Subject: [PATCH 23/32] fix: load source map from sourceMappingURL comment (#1327) ..and feed it into the `transform` hook. --- packages/vite/package.json | 2 ++ packages/vite/src/node/server/transformRequest.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/vite/package.json b/packages/vite/package.json index e4d0feec7ee8cc..2df9b7d6398d0d 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -59,6 +59,7 @@ "@rollup/plugin-typescript": "^8.0.0", "@rollup/pluginutils": "^4.1.0", "@types/clean-css": "^4.2.3", + "@types/convert-source-map": "^1.5.1", "@types/debug": "^4.1.5", "@types/es-module-lexer": "^0.3.0", "@types/estree": "^0.0.45", @@ -77,6 +78,7 @@ "clean-css": "^4.2.3", "connect": "^3.7.0", "connect-history-api-fallback": "^1.6.0", + "convert-source-map": "^1.7.0", "cors": "^2.8.5", "debug": "^4.3.1", "dotenv": "^8.2.0", diff --git a/packages/vite/src/node/server/transformRequest.ts b/packages/vite/src/node/server/transformRequest.ts index cca76aef8c48f2..1a200153c06e6c 100644 --- a/packages/vite/src/node/server/transformRequest.ts +++ b/packages/vite/src/node/server/transformRequest.ts @@ -1,5 +1,7 @@ import { promises as fs } from 'fs' +import path from 'path' import getEtag from 'etag' +import * as convertSourceMap from 'convert-source-map' import { SourceDescription, SourceMap } from 'rollup' import { ViteDevServer } from '..' import chalk from 'chalk' @@ -58,6 +60,12 @@ export async function transformRequest( throw e } } + if (code) { + map = ( + convertSourceMap.fromSource(code) || + convertSourceMap.fromMapFileSource(code, path.dirname(file)) + )?.toObject() + } } else { isDebug && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`) if (typeof loadResult === 'object') { @@ -80,7 +88,7 @@ export async function transformRequest( // transform const transformStart = Date.now() - const transformResult = await pluginContainer.transform(code, id) + const transformResult = await pluginContainer.transform(code, id, map) if ( transformResult == null || (typeof transformResult === 'object' && transformResult.code == null) From 25adf1eefaf6817f9443365f5ee3fcf0d63ffd6f Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 16:47:05 -0500 Subject: [PATCH 24/32] fix: do not error on css deep imports --- packages/vite/src/node/plugins/resolve.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index a2d54e522ef31d..3206e5e6a7cba4 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -19,6 +19,7 @@ import slash from 'slash' import { createFilter } from '@rollup/pluginutils' import { PartialResolvedId } from 'rollup' import isBuiltin from 'isbuiltin' +import { isCSSRequest } from './css' const mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main'] @@ -212,7 +213,8 @@ export function tryNodeResolve( deepMatch && server && server.optimizeDepsMetadata && - pkg.data.name in server.optimizeDepsMetadata.map + pkg.data.name in server.optimizeDepsMetadata.map && + !isCSSRequest(id) ) { throw new Error( chalk.yellow( From 2286f629ab6d96fb0b90c9825582962bf8f0f2a5 Mon Sep 17 00:00:00 2001 From: Ian Purvis Date: Sun, 3 Jan 2021 16:06:58 -0600 Subject: [PATCH 25/32] feat(wasm): use `instantiateStreaming` when available (#1330) close #1143 --- .../playground/wasm/__tests__/wasm.spec.ts | 11 +++-- packages/playground/wasm/heavy.wasm | Bin 0 -> 4274 bytes packages/playground/wasm/heavy.wasm.map | 1 + packages/playground/wasm/index.html | 38 +++++++++++++----- .../wasm/{simple.wasm => light.wasm} | Bin packages/vite/src/node/plugins/wasm.ts | 23 +++++++---- 6 files changed, 54 insertions(+), 19 deletions(-) create mode 100644 packages/playground/wasm/heavy.wasm create mode 100644 packages/playground/wasm/heavy.wasm.map rename packages/playground/wasm/{simple.wasm => light.wasm} (100%) diff --git a/packages/playground/wasm/__tests__/wasm.spec.ts b/packages/playground/wasm/__tests__/wasm.spec.ts index d68e9109dad167..b292f0ddc6e7f8 100644 --- a/packages/playground/wasm/__tests__/wasm.spec.ts +++ b/packages/playground/wasm/__tests__/wasm.spec.ts @@ -1,6 +1,11 @@ import { untilUpdated } from '../../testUtils' -test('should work', async () => { - await page.click('.run') - await untilUpdated(() => page.textContent('.result'), 'Wasm result: 42') +test('should work when inlined', async () => { + await page.click('.inline-wasm .run') + await untilUpdated(() => page.textContent('.inline-wasm .result'), '42') +}) + +test('should work when output', async () => { + await page.click('.output-wasm .run') + await untilUpdated(() => page.textContent('.output-wasm .result'), '24') }) diff --git a/packages/playground/wasm/heavy.wasm b/packages/playground/wasm/heavy.wasm new file mode 100644 index 0000000000000000000000000000000000000000..e9de33548e4030bfd0a6cae1a4ce7995771e6d36 GIT binary patch literal 4274 zcmeI$Jqp4w6bJDCYip~cQf@P5cwM+upHr)~W!Wod8 zT)rK@%8pG4Nub*&7jr#dugT1V5Kmucdg9^3)3-L6ChGI_mA-lN8?XU3zy{a=8(;%$ tfDNz#Hoykh02}yk0~mQ#QI~PDluD)fe!W_F!T6BK(=|BjpNb%p>I2=*l8pcW literal 0 HcmV?d00001 diff --git a/packages/playground/wasm/heavy.wasm.map b/packages/playground/wasm/heavy.wasm.map new file mode 100644 index 00000000000000..1bbe507af63f4e --- /dev/null +++ b/packages/playground/wasm/heavy.wasm.map @@ -0,0 +1 @@ +{"version":3,"sources":["~lib/rt/common.ts","~lib/shared/typeinfo.ts","assembly/index.ts"],"names":[],"mappings":"oGEIE,AAAc","sourceRoot":"./heavy.wasm","sourcesContent":["// Alignment guarantees\n\n// @ts-ignore: decorator\n@inline export const AL_BITS: u32 = 4; // 16 bytes to fit up to v128\n// @ts-ignore: decorator\n@inline export const AL_SIZE: usize = 1 << AL_BITS;\n// @ts-ignore: decorator\n@inline export const AL_MASK: usize = AL_SIZE - 1;\n\n// Extra debugging\n\n// @ts-ignore: decorator\n@inline export const DEBUG = true;\n// @ts-ignore: decorator\n@inline export const TRACE = false;\n\n// Memory manager\n\n// ╒════════════ Memory manager block layout (32-bit) ═════════════╕\n// 3 2 1\n// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits\n// ├─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤\n// │ MM info │ -4\n// ╞>ptr═══════════════════════════════════════════════════════════╡\n// │ ... │\n@unmanaged export class BLOCK {\n /** Memory manager info. */\n mmInfo: usize;\n}\n\n/** Overhead of a memory manager block. */\n// @ts-ignore: decorator\n@inline export const BLOCK_OVERHEAD: usize = offsetof();\n\n/** Maximum size of a memory manager block's payload. */\n// @ts-ignore: decorator\n@inline export const BLOCK_MAXSIZE: usize = (1 << 30) - BLOCK_OVERHEAD;\n\n// Garbage collector\n\n// ╒══════════ Garbage collector object layout (32-bit) ═══════════╕\n// 3 2 1\n// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits\n// ├─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤\n// │ Memory manager block │ -20\n// ╞═══════════════════════════════════════════════════════════════╡\n// │ GC info │ -16\n// ├───────────────────────────────────────────────────────────────┤\n// │ GC info │ -12\n// ├───────────────────────────────────────────────────────────────┤\n// │ RT id │ -8\n// ├───────────────────────────────────────────────────────────────┤\n// │ RT size │ -4\n// ╞>ptr═══════════════════════════════════════════════════════════╡\n// │ ... │\n@unmanaged export class OBJECT extends BLOCK {\n /** Garbage collector info. */\n gcInfo: u32;\n /** Garbage collector info. */\n gcInfo2: u32;\n /** Runtime class id. */\n rtId: u32;\n /** Runtime object size. */\n rtSize: u32;\n}\n\n/** Overhead of a garbage collector object. Excludes memory manager block overhead. */\n// @ts-ignore: decorator\n@inline export const OBJECT_OVERHEAD: usize = (offsetof() - BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK;\n\n/** Maximum size of a garbage collector object's payload. */\n// @ts-ignore: decorator\n@inline export const OBJECT_MAXSIZE: usize = BLOCK_MAXSIZE - OBJECT_OVERHEAD;\n\n/** Total of memory manager and garbage collector overhead. */\n// @ts-ignore: decorator\n@inline export const TOTAL_OVERHEAD: usize = BLOCK_OVERHEAD + OBJECT_OVERHEAD;\n","// This file is shared with the compiler and must remain portable\n\n// ╒═══════════════════ Typeinfo interpretation ═══════════════════╕\n// 3 2 1\n// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits\n// ├─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤ ◄─ __rtti_base\n// │ count │\n// ╞═══════════════════════════════════════════════════════════════╡ ┐\n// │ Typeinfo#flags [id=0] │ id < count\n// ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤\n// │ Typeinfo#base [id=0] │\n// ├───────────────────────────────────────────────────────────────┤\n// │ ... │\n\n/** Runtime type information data structure. */\n@unmanaged\nexport class Typeinfo {\n /** Flags describing the shape of this class type. */\n flags: TypeinfoFlags = TypeinfoFlags.NONE;\n /** Base class id or `0` if none. */\n base: u32 = 0;\n}\n\n/** Runtime type information flags. */\nexport const enum TypeinfoFlags {\n /** No specific flags. */\n NONE = 0,\n /** Type is an `ArrayBufferView`. */\n ARRAYBUFFERVIEW = 1 << 0,\n /** Type is an `Array`. */\n ARRAY = 1 << 1,\n /** Type is a `StaticArray`. */\n STATICARRAY = 1 << 2,\n /** Type is a `Set`. */\n SET = 1 << 3,\n /** Type is a `Map`. */\n MAP = 1 << 4,\n /** Type is inherently acyclic. */\n ACYCLIC = 1 << 5,\n /** Value alignment of 1 byte. */\n VALUE_ALIGN_0 = 1 << 6,\n /** Value alignment of 2 bytes. */\n VALUE_ALIGN_1 = 1 << 7,\n /** Value alignment of 4 bytes. */\n VALUE_ALIGN_2 = 1 << 8,\n /** Value alignment of 8 bytes. */\n VALUE_ALIGN_3 = 1 << 9,\n /** Value alignment of 16 bytes. */\n VALUE_ALIGN_4 = 1 << 10,\n /** Value is a signed type. */\n VALUE_SIGNED = 1 << 11,\n /** Value is a float type. */\n VALUE_FLOAT = 1 << 12,\n /** Value type is nullable. */\n VALUE_NULLABLE = 1 << 13,\n /** Value type is managed. */\n VALUE_MANAGED = 1 << 14,\n /** Key alignment of 1 byte. */\n KEY_ALIGN_0 = 1 << 15,\n /** Key alignment of 2 bytes. */\n KEY_ALIGN_1 = 1 << 16,\n /** Key alignment of 4 bytes. */\n KEY_ALIGN_2 = 1 << 17,\n /** Key alignment of 8 bytes. */\n KEY_ALIGN_3 = 1 << 18,\n /** Key alignment of 16 bytes. */\n KEY_ALIGN_4 = 1 << 19,\n /** Key is a signed type. */\n KEY_SIGNED = 1 << 20,\n /** Key is a float type. */\n KEY_FLOAT = 1 << 21,\n /** Key type is nullable. */\n KEY_NULLABLE = 1 << 22,\n /** Key type is managed. */\n KEY_MANAGED = 1 << 23\n}\n","// The entry file of your WebAssembly module.\nimport { imported_func } from './imports'\n\nexport function exported_func(): void {\n imported_func(24);\n}\n\nconst noInline = '🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩🍩'\n"]} \ No newline at end of file diff --git a/packages/playground/wasm/index.html b/packages/playground/wasm/index.html index 5d16b9be15c6c3..0e57ccb0cc6e4b 100644 --- a/packages/playground/wasm/index.html +++ b/packages/playground/wasm/index.html @@ -1,16 +1,36 @@ - -
+

Web Assembly

+ +
+

When wasm is inline, result should be 42

+ + +
+ +
+

When wasm is output, result should be 24

+ + +
diff --git a/packages/playground/wasm/simple.wasm b/packages/playground/wasm/light.wasm similarity index 100% rename from packages/playground/wasm/simple.wasm rename to packages/playground/wasm/light.wasm diff --git a/packages/vite/src/node/plugins/wasm.ts b/packages/vite/src/node/plugins/wasm.ts index d18950e63633f6..753dc1813817c0 100644 --- a/packages/vite/src/node/plugins/wasm.ts +++ b/packages/vite/src/node/plugins/wasm.ts @@ -4,8 +4,8 @@ import { fileToUrl } from './asset' const wasmHelperId = '/__vite-wasm-helper' -const wasmHelper = (opts = {}, url: string) => { - let instance +const wasmHelper = async (opts = {}, url: string) => { + let result if (url.startsWith('data:')) { // @ts-ignore const binaryString = atob(url.replace(/^data:.*?base64,/, '')) @@ -14,7 +14,7 @@ const wasmHelper = (opts = {}, url: string) => { bytes[i] = binaryString.charCodeAt(i) } // @ts-ignore - instance = WebAssembly.instantiate(bytes.buffer, opts) + result = await WebAssembly.instantiate(bytes, opts) } else { // https://github.com/mdn/webassembly-examples/issues/5 // WebAssembly.instantiateStreaming requires the server to provide the @@ -22,13 +22,22 @@ const wasmHelper = (opts = {}, url: string) => { // a lot of static file servers, so we just work around it by getting the // raw buffer. // @ts-ignore - instance = fetch(url) + const response = await fetch(url) + const contentType = response.headers.get('Content-Type') || '' + if ( // @ts-ignore - .then((r) => r.arrayBuffer()) + 'instantiateStreaming' in WebAssembly && + contentType.startsWith('application/wasm') + ) { // @ts-ignore - .then((bytes) => WebAssembly.instantiate(bytes, opts)) + result = await WebAssembly.instantiateStreaming(response, opts) + } else { + const buffer = await response.arrayBuffer() + // @ts-ignore + result = await WebAssembly.instantiate(buffer, opts) + } } - return instance.then((i: any) => i.instance.exports) + return result.instance.exports } const wasmHelperCode = wasmHelper.toString() From c4f9adc464fc3376ad9afab84258df15747a18d5 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 17:18:34 -0500 Subject: [PATCH 26/32] chore: fix readme ci links [skip ci] --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 38948899e124cf..5c91aa84763cf5 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ MIT [npm-url]: https://npmjs.com/package/vite [node-img]: https://img.shields.io/node/v/vite.svg [node-url]: https://nodejs.org/en/about/releases/ -[unix-ci-img]: https://circleci.com/gh/vitejs/vite/tree/2.0.svg?style=shield -[unix-ci-url]: https://app.circleci.com/pipelines/github/vitejs/vite?branch=2.0 -[windows-ci-img]: https://ci.appveyor.com/api/projects/status/0q4j8062olbcs71l/branch/2.0?svg=true -[windows-ci-url]: https://ci.appveyor.com/project/yyx990803/vite/branch/2.0 +[unix-ci-img]: https://circleci.com/gh/vitejs/vite/tree/main.svg?style=shield +[unix-ci-url]: https://app.circleci.com/pipelines/github/vitejs/vite?branch=main +[windows-ci-img]: https://ci.appveyor.com/api/projects/status/0q4j8062olbcs71l/branch/main?svg=true +[windows-ci-url]: https://ci.appveyor.com/project/yyx990803/vite/branch/main From f6e7c0ff4fbc30ceba4149835d9380ba1e8fcaa4 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 20:58:43 -0500 Subject: [PATCH 27/32] chore: lockfile --- yarn.lock | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/yarn.lock b/yarn.lock index ff65ccb6850382..d65430302fbb2f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -859,6 +859,11 @@ "@types/node" "*" source-map "^0.6.0" +"@types/convert-source-map@^1.5.1": + version "1.5.1" + resolved "https://registry.yarnpkg.com/@types/convert-source-map/-/convert-source-map-1.5.1.tgz#d4d180dd6adc5cb68ad99bd56e03d637881f4616" + integrity sha512-laiDIXqqthjJlyAMYAXOtN3N8+UlbM+KvZi4BaY5ZOekmVkBs/UxfK5O0HWeJVG2eW8F+Mu2ww13fTX+kY1FlQ== + "@types/debug@^4.1.5": version "4.1.5" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.5.tgz#b14efa8852b7768d898906613c23f688713e02cd" From 2b82e84a272db2a4269d742dd7b9a8a1ad8351dd Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 20:59:26 -0500 Subject: [PATCH 28/32] fix: ensure consistent module entry urls by removing import query fix #1321 --- packages/vite/src/node/server/moduleGraph.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/server/moduleGraph.ts b/packages/vite/src/node/server/moduleGraph.ts index 2997e7a2a54bcb..c42136b7c68a19 100644 --- a/packages/vite/src/node/server/moduleGraph.ts +++ b/packages/vite/src/node/server/moduleGraph.ts @@ -1,6 +1,11 @@ import { extname } from 'path' import { isDirectCSSRequest } from '../plugins/css' -import { cleanUrl, normalizePath, removeTimestampQuery } from '../utils' +import { + cleanUrl, + normalizePath, + removeImportQuery, + removeTimestampQuery +} from '../utils' import { TransformResult } from './transformRequest' import { PluginContainer } from './pluginContainer' import { parse as parseUrl } from 'url' @@ -155,7 +160,7 @@ export class ModuleGraph { // 2. resolve its extension so that urls with or without extension all map to // the same module async resolveUrl(url: string): Promise<[string, string]> { - url = removeTimestampQuery(url) + url = removeImportQuery(removeTimestampQuery(url)) const resolvedId = (await this.container.resolveId(url))?.id || url const ext = extname(cleanUrl(resolvedId)) const { pathname, search, hash } = parseUrl(url) From 0a94c88238f265a14c116c2f1306d3be74b182e6 Mon Sep 17 00:00:00 2001 From: Matias Capeletto Date: Mon, 4 Jan 2021 03:17:13 +0100 Subject: [PATCH 29/32] fix: @fs paths resolving for win32 (#1317) --- packages/vite/src/node/plugins/resolve.ts | 4 ++-- packages/vite/src/node/utils.ts | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 3206e5e6a7cba4..165620722cb2fc 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -12,6 +12,7 @@ import { isExternalUrl, isObject, normalizePath, + fsPathFromId, resolveFrom } from '../utils' import { ViteDevServer } from '..' @@ -60,8 +61,7 @@ export function resolvePlugin({ // explicit fs paths that starts with /@fs/* if (asSrc && id.startsWith(FS_PREFIX)) { - let fsPath = id.slice(FS_PREFIX.length - 1) - if (fsPath.startsWith('//')) fsPath = fsPath.slice(1) + const fsPath = fsPathFromId(id) res = tryFsResolve(fsPath, false) isDebug && debug(`[@fs] ${chalk.cyan(id)} -> ${chalk.dim(res)}`) // always return here even if res doesn't exist since /@fs/ is explicit diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index f2b617de8d04f1..1518b5c8d38a88 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -59,6 +59,11 @@ export function normalizePath(id: string): string { return path.posix.normalize(id) } +export function fsPathFromId(id: string): string { + const fsPath = normalizePath(id.slice(FS_PREFIX.length)) + return fsPath.startsWith('/') ? fsPath : `/${fsPath}` +} + export const queryRE = /\?.*$/ export const hashRE = /#.*$/ From 409988fbbb5d854ccbbae0dd81f757eb42e24c40 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 22:02:43 -0500 Subject: [PATCH 30/32] fix(resolve): always prioritize browser field --- packages/vite/src/node/plugins/resolve.ts | 48 +++++++++++++++-------- packages/vite/src/node/tsconfig.json | 1 + 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 165620722cb2fc..f1471def6256f5 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -22,7 +22,7 @@ import { PartialResolvedId } from 'rollup' import isBuiltin from 'isbuiltin' import { isCSSRequest } from './css' -const mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main'] +const mainFields = ['module', 'jsnext', 'jsnext:main', 'main'] const isDebug = process.env.DEBUG const debug = createDebugger('vite:resolve-details', { @@ -85,7 +85,7 @@ export function resolvePlugin({ let fsPath = path.resolve(basedir, id) // handle browser field mapping for relative imports const pkg = importer && idToPkgMap.get(importer) - if (pkg && pkg.data.browser) { + if (pkg && isObject(pkg.data.browser)) { const pkgRealtivePath = './' + slash(path.relative(pkg.dir, fsPath)) fsPath = path.resolve( pkg.dir, @@ -280,6 +280,9 @@ export interface PackageData { data: { [field: string]: any version: string + main: string + module: string + browser: string | Record exports: string | Record | string[] dependencies: Record } @@ -331,19 +334,30 @@ export function resolvePackageEntry( ): string | undefined { let entryPoint: string | undefined - // resolve exports field - // https://nodejs.org/api/packages.html#packages_package_entry_points - const { exports: exportsField } = data - if (exportsField) { - if (typeof exportsField === 'string') { - entryPoint = exportsField - } else if (Array.isArray(exportsField)) { - entryPoint = exportsField[0] - } else if (isObject(exportsField)) { - if ('.' in exportsField) { - entryPoint = resolveConditionalExports(exportsField['.']) - } else { - entryPoint = resolveConditionalExports(exportsField) + // check browser field first with highest priority + const browserEntry = + typeof data.browser === 'string' + ? data.browser + : isObject(data.browser) && data.browser['.'] + if (browserEntry) { + entryPoint = browserEntry + } + + if (!entryPoint) { + // resolve exports field + // https://nodejs.org/api/packages.html#packages_package_entry_points + const { exports: exportsField } = data + if (exportsField) { + if (typeof exportsField === 'string') { + entryPoint = exportsField + } else if (Array.isArray(exportsField)) { + entryPoint = exportsField[0] + } else if (isObject(exportsField)) { + if ('.' in exportsField) { + entryPoint = resolveConditionalExports(exportsField['.']) + } else { + entryPoint = resolveConditionalExports(exportsField) + } } } } @@ -362,7 +376,7 @@ export function resolvePackageEntry( // resolve object browser field in package.json // https://github.com/defunctzombie/package-browser-field-spec const { browser: browserField } = data - if (browserField && typeof browserField === 'object') { + if (isObject(browserField)) { entryPoint = mapWithBrowserField(entryPoint, browserField) } @@ -404,7 +418,7 @@ function resolveDeepImport( `${path.join(dir, 'package.json')}.` ) } - } else if (browserField) { + } else if (isObject(browserField)) { relativeId = mapWithBrowserField(relativeId, browserField) } diff --git a/packages/vite/src/node/tsconfig.json b/packages/vite/src/node/tsconfig.json index 65620f9fd4e226..456e6f2849d95d 100644 --- a/packages/vite/src/node/tsconfig.json +++ b/packages/vite/src/node/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig.base.json", "include": ["./", "../../types"], + "exclude": ["**/__tests__"], "compilerOptions": { // compile away optional-chaining-operator // node support table: https://node.green/#ES2020-features-optional-chaining-operator----- From b5b14962b53d8dcbae850b9eb6abf2ca5820b3db Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 22:26:34 -0500 Subject: [PATCH 31/32] feat: esbuild.(include|exclude|jsxInject) --- docs/config/index.md | 18 ++++++++++--- docs/guide/features.md | 15 ++++++++--- packages/playground/react/App.jsx | 2 +- packages/playground/react/vite.config.js | 5 +++- packages/vite/src/node/config.ts | 8 ++---- packages/vite/src/node/plugins/esbuild.ts | 33 ++++++++++++++++------- 6 files changed, 56 insertions(+), 25 deletions(-) diff --git a/docs/config/index.md b/docs/config/index.md index b6dd42168773bc..7c3fec79cf2903 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -133,9 +133,9 @@ export default ({ command, mode }) => { ### esbuild -- **Type:** `ESBuildTransformOptions | ((file: string) => ESBuildTransformOptions) | false` +- **Type:** `ESBuildOptions | false` - Specify [esbuild transform options](https://esbuild.github.io/api/#transform-api). The most common use case is customizing JSX: + `ESBuildOptions` extends [ESbuild's own transform options](https://esbuild.github.io/api/#transform-api). The most common use case is customizing JSX: ```js export default { @@ -146,9 +146,19 @@ export default ({ command, mode }) => { } ``` - The option can also be a function to conditionally return options based on the name of the file being transformed. + By default, ESBuild is applied to `ts`, `jsx` and `tsx` files. You can customize this with `esbuild.include` and `esbuild.exclude`, both of which expects type of `string | RegExp | (string | RegExp)[]`. - Set to `false` to disable ESbuild transforms (applies to `.ts`. `.tsx` and `.jsx` files by default). + In addition, you can also use `esbuild.jsxInject` to automatically inject JSX helper imports for every file transformed by ESBuild: + + ```js + export default { + esbuild: { + jsxInject: `import React from 'react'` + } + } + ``` + + Set to `false` to disable ESbuild transforms. ### assetsInclude diff --git a/docs/guide/features.md b/docs/guide/features.md index 5c9c3150be7d7c..c9fef7f5c949c7 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -34,7 +34,7 @@ Note that because `esbuild` only performs transpilation without type information ## JSX -`.jsx` and `.tsx` files are also supported out of the box. JSX transpilation is also handled via `esbuild`, and defaults to the React 16 flavor. React 17 style JSX support in esbuild is tracked [here](https://github.com/evanw/esbuild/issues/334). +`.jsx` and `.tsx` files are also supported out of the box. JSX transpilation is also handled via [ESBuild](https://esbuild.github.io), and defaults to the React 16 flavor. React 17 style JSX support in ESBuild is tracked [here](https://github.com/evanw/esbuild/issues/334). If not using JSX with React, custom `jsxFactory` and `jsxFragment` can be configured using the [`esbuild` option](/config/#esbuild). For example for Preact: @@ -48,9 +48,18 @@ export default { } ``` -More details in [esbuild docs](https://esbuild.github.io/content-types/#jsx). +More details in [ESBuild docs](https://esbuild.github.io/content-types/#jsx). -A custom plugin can also auto inject the helpers in every file to avoid having to manually import them. See the [Plugin API](./api-plugin) on how to write such a plugin. +You can inject the JSX helpers using `jsxInject` to avoid manual imports, which is a Vite-only option: + +```js +// vite.config.js +export default { + esbuild: { + jsxInject: `import React from 'react'` + } +} +``` ## CSS diff --git a/packages/playground/react/App.jsx b/packages/playground/react/App.jsx index 07507ff346a8a7..ef0ee76f43fcc5 100644 --- a/packages/playground/react/App.jsx +++ b/packages/playground/react/App.jsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react' +import { useState } from 'react' function App() { const [count, setCount] = useState(0) diff --git a/packages/playground/react/vite.config.js b/packages/playground/react/vite.config.js index 9ae0cf90f57f96..98b19aea89cea0 100644 --- a/packages/playground/react/vite.config.js +++ b/packages/playground/react/vite.config.js @@ -4,5 +4,8 @@ const reactRefresh = require('@vitejs/plugin-react-refresh') * @type {import('vite').UserConfig} */ module.exports = { - plugins: [reactRefresh()] + plugins: [reactRefresh()], + esbuild: { + jsxInject: `import React from 'react'` + } } diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 8c6d13405b9a13..07119e5b93070e 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -8,8 +8,7 @@ import { CSSOptions } from './plugins/css' import { createDebugger, isObject, lookupFile, normalizePath } from './utils' import { resolvePlugins } from './plugins' import chalk from 'chalk' -import { esbuildPlugin } from './plugins/esbuild' -import { TransformOptions as ESbuildTransformOptions } from 'esbuild' +import { ESBuildOptions, esbuildPlugin } from './plugins/esbuild' import dotenv from 'dotenv' import dotenvExpand from 'dotenv-expand' import { Alias, AliasOptions } from 'types/alias' @@ -67,10 +66,7 @@ export interface UserConfig { * Transform options to pass to esbuild. * Or set to `false` to disable esbuild. */ - esbuild?: - | ESbuildTransformOptions - | ((file: string) => ESbuildTransformOptions) - | false + esbuild?: ESBuildOptions | false /** * Specify additional files to be treated as source file (included into the * transform pipeline). diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index 95984cbebac2db..895ebcbcc10628 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -12,12 +12,19 @@ import { createDebugger, generateCodeFrame } from '../utils' import merge from 'merge-source-map' import { SourceMap } from 'rollup' import { ResolvedConfig } from '..' +import { createFilter } from '@rollup/pluginutils' const debug = createDebugger('vite:esbuild') // lazy start the service let _servicePromise: Promise | undefined +export interface ESBuildOptions extends TransformOptions { + include?: string | RegExp | string[] | RegExp[] + exclude?: string | RegExp | string[] | RegExp[] + jsxInject?: string +} + export async function ensureService() { if (!_servicePromise) { _servicePromise = require('esbuild').startService() @@ -40,22 +47,22 @@ export type EsbuildTransformResult = Omit & { export async function transformWithEsbuild( code: string, filename: string, - options?: TransformOptions | ((file: string) => TransformOptions), + options?: TransformOptions, inMap?: object ): Promise { const service = await ensureService() - if (typeof options === 'function') { - options = options(filename) - } - const resolvedOptions = { loader: path.extname(filename).slice(1) as Loader, sourcemap: true, // ensure source file name contains full query sourcefile: filename, ...options - } + } as ESBuildOptions + + delete resolvedOptions.include + delete resolvedOptions.exclude + delete resolvedOptions.jsxInject try { const result = await service.transform(code, resolvedOptions) @@ -88,19 +95,25 @@ export async function transformWithEsbuild( } } -export function esbuildPlugin( - options: TransformOptions | ((file: string) => TransformOptions) = {} -): Plugin { +export function esbuildPlugin(options: ESBuildOptions = {}): Plugin { + const filter = createFilter( + options.include || /\.(tsx?|jsx)$/, + options.exclude + ) + return { name: 'vite:esbuild', async transform(code, id) { - if (/\.(tsx?|jsx)$/.test(id)) { + if (filter(id)) { const result = await transformWithEsbuild(code, id, options) if (result.warnings.length) { result.warnings.forEach((m) => { this.warn(prettifyMessage(m, code)) }) } + if (options.jsxInject) { + result.code = options.jsxInject + ';' + result.code + } return { code: result.code, map: result.map From 0fef0338db78d0a72cd5f73e83911245dfed3c3e Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 3 Jan 2021 22:39:09 -0500 Subject: [PATCH 32/32] release: plugin-vue@1.0.4 --- packages/plugin-vue/CHANGELOG.md | 14 ++++++++++++++ packages/plugin-vue/package.json | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/plugin-vue/CHANGELOG.md b/packages/plugin-vue/CHANGELOG.md index b941e0bfb5fdee..3e288f38fcea46 100644 --- a/packages/plugin-vue/CHANGELOG.md +++ b/packages/plugin-vue/CHANGELOG.md @@ -1,3 +1,17 @@ +## [1.0.4](https://github.com/vitejs/vite/compare/plugin-vue@1.0.3...plugin-vue@1.0.4) (2021-01-04) + + +### Bug Fixes + +* **plugin-vue:** mark SFC compiler options as `Partial` ([#1316](https://github.com/vitejs/vite/issues/1316)) ([331484c](https://github.com/vitejs/vite/commit/331484c2600e96543aa8007b4940d023cb5cc19f)) + + +### Features + +* **plugin-vue:** export vue query parse API ([#1303](https://github.com/vitejs/vite/issues/1303)) ([56bcb0c](https://github.com/vitejs/vite/commit/56bcb0c475a5dff31527cad6dcd7c61fde424f5e)) + + + ## [1.0.3](https://github.com/vitejs/vite/compare/plugin-vue@1.0.2...plugin-vue@1.0.3) (2021-01-02) diff --git a/packages/plugin-vue/package.json b/packages/plugin-vue/package.json index 2a190e67cd57ce..ccb7f30589d271 100644 --- a/packages/plugin-vue/package.json +++ b/packages/plugin-vue/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-vue", - "version": "1.0.3", + "version": "1.0.4", "license": "MIT", "author": "Evan You", "files": [