Skip to content

Commit

Permalink
Merge branch 'main' into remove-internal-exports
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Oct 13, 2023
2 parents 5a3bd44 + cd82648 commit a3f7035
Show file tree
Hide file tree
Showing 28 changed files with 426 additions and 148 deletions.
8 changes: 8 additions & 0 deletions docs/guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ interface ViteHotContext {
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
off<T extends string>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
}
```
Expand Down Expand Up @@ -181,6 +185,10 @@ The following HMR events are dispatched by Vite automatically:
Custom HMR events can also be sent from plugins. See [handleHotUpdate](./api-plugin#handlehotupdate) for more details.
## `hot.off(event, cb)`
Remove callback from the event listeners
## `hot.send(event, data)`
Send custom events back to Vite's dev server.
Expand Down
4 changes: 0 additions & 4 deletions docs/guide/dep-pre-bundling.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@ export default defineConfig({
When making changes to the linked dep, restart the dev server with the `--force` command line option for the changes to take effect.
::: warning Deduping
Due to differences in linked dependency resolution, transitive dependencies can deduplicate incorrectly, causing issues when used in runtime. If you stumble on this issue, use `npm pack` on the linked dependency to fix it.
:::
## Customizing the Behavior
The default dependency discovery heuristics may not always be desirable. In cases where you want to explicitly include/exclude dependencies from the list, use the [`optimizeDeps` config options](/config/dep-optimization-options.md).
Expand Down
2 changes: 2 additions & 0 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Also there are other breaking changes which only affect few users.
- Removed accidentally exported internal APIs: `isDepsOptimizerEnabled` and `getDepOptimizationConfig`
- Removed exported internal types: `DepOptimizationResult`, `DepOptimizationProcessing`, and `DepsOptimizer`
- Renamed `ResolveWorkerOptions` type to `ResolvedWorkerOptions`
- [[#5657] fix: return 404 for resources requests outside the base path](https://github.com/vitejs/vite/pull/5657)
- In the past, Vite responded to requests outside the base path without `Accept: text/html`, as if they were requested with the base path. Vite no longer does that and responds with 404 instead.

## Migration from v3

Expand Down
15 changes: 15 additions & 0 deletions packages/vite/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
## 5.0.0-beta.7 (2023-10-12)

* feat: add off method to ViteHotContext (issue #14185) (#14518) ([31333bb](https://github.com/vitejs/vite/commit/31333bb)), closes [#14185](https://github.com/vitejs/vite/issues/14185) [#14518](https://github.com/vitejs/vite/issues/14518)
* feat: show better parse error in build (#14600) ([84df7db](https://github.com/vitejs/vite/commit/84df7db)), closes [#14600](https://github.com/vitejs/vite/issues/14600)
* chore(config): improve the readability of warning messages (#14594) ([b43b4df](https://github.com/vitejs/vite/commit/b43b4df)), closes [#14594](https://github.com/vitejs/vite/issues/14594)
* fix: off-by-one bug in HTML whitespace removal (#14589) ([f54e6d8](https://github.com/vitejs/vite/commit/f54e6d8)), closes [#14589](https://github.com/vitejs/vite/issues/14589)
* fix(html): import expression in classic script for dev (#14595) ([ea47b8f](https://github.com/vitejs/vite/commit/ea47b8f)), closes [#14595](https://github.com/vitejs/vite/issues/14595)
* fix(html): inline style attribute not working in dev (#14592) ([a4a17b8](https://github.com/vitejs/vite/commit/a4a17b8)), closes [#14592](https://github.com/vitejs/vite/issues/14592)
* fix(html): relative paths without leading dot wasn't rewritten (#14591) ([0a38e3b](https://github.com/vitejs/vite/commit/0a38e3b)), closes [#14591](https://github.com/vitejs/vite/issues/14591)
* fix(proxy): correct the logic of bypass returning false (#14579) ([261633a](https://github.com/vitejs/vite/commit/261633a)), closes [#14579](https://github.com/vitejs/vite/issues/14579)
* build: clean generated type file (#14582) ([fffe16e](https://github.com/vitejs/vite/commit/fffe16e)), closes [#14582](https://github.com/vitejs/vite/issues/14582)
* build: use rollup-plugin-dts (#14571) ([d89725b](https://github.com/vitejs/vite/commit/d89725b)), closes [#14571](https://github.com/vitejs/vite/issues/14571)



## 5.0.0-beta.6 (2023-10-10)

* refactor(css): make `getEmptyChunkReplacer` for unit test (#14528) ([18900fd](https://github.com/vitejs/vite/commit/18900fd)), closes [#14528](https://github.com/vitejs/vite/issues/14528)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vite",
"version": "5.0.0-beta.6",
"version": "5.0.0-beta.7",
"type": "module",
"license": "MIT",
"author": "Evan You",
Expand Down
95 changes: 92 additions & 3 deletions packages/vite/rollup.dts.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { findStaticImports } from 'mlly'
import { type Plugin, defineConfig } from 'rollup'
import dts from 'rollup-plugin-dts'

Expand Down Expand Up @@ -28,12 +29,34 @@ const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g
const singlelineCommentsRE = /\/\/[^/].*/g
const licenseCommentsRE = /MIT License|MIT license|BSD license/
const consecutiveNewlinesRE = /\n{2,}/g
const identifierWithTrailingDollarRE = /\b(\w+)\$\d+\b/g

/**
* Replace specific identifiers with a more readable name, grouped by
* the module that imports the identifer as a named import alias
*/
const identifierReplacements: Record<string, Record<string, string>> = {
rollup: {
Plugin$1: 'rollup.Plugin',
TransformResult$2: 'rollup.TransformResult',
},
esbuild: {
TransformResult$1: 'esbuild_TransformResult',
TransformOptions$1: 'esbuild_TransformOptions',
BuildOptions$1: 'esbuild_BuildOptions',
},
'node:https': {
Server$1: 'HttpsServer',
ServerOptions$1: 'HttpsServerOptions',
},
}

/**
* Patch the types files before passing to dts plugin
* 1. Resolve `dep-types/*` and `types/*` imports
* 2. Validate unallowed dependency imports
* 3. Clean unnecessary comments
* 3. Replace confusing type names
* 4. Clean unnecessary comments
*/
function patchTypes(): Plugin {
return {
Expand All @@ -56,8 +79,8 @@ function patchTypes(): Plugin {
}
},
renderChunk(code, chunk) {
const deps = new Set(Object.keys(pkg.dependencies))
// Validate that chunk imports do not import dev deps
const deps = new Set(Object.keys(pkg.dependencies))
for (const id of chunk.imports) {
if (
!id.startsWith('./') &&
Expand All @@ -72,13 +95,79 @@ function patchTypes(): Plugin {
}
}

// Rollup deduplicate type names with a trailing `$1` or `$2`, which can be
// confusing when showed in autocompletions. Try to replace with a better name
const imports = findStaticImports(code)
for (const modName in identifierReplacements) {
const imp = imports.find(
(imp) => imp.specifier === modName && imp.imports.includes('{'),
)
// Validate that `identifierReplacements` is not outdated if there's no match
if (!imp) {
this.warn(
`${chunk.fileName} does not import "${modName}" for replacement`,
)
process.exitCode = 1
continue
}

const replacements = identifierReplacements[modName]
for (const id in replacements) {
// Validate that `identifierReplacements` is not outdated if there's no match
if (!imp.imports.includes(id)) {
this.warn(
`${chunk.fileName} does not import "${id}" from "${modName}" for replacement`,
)
process.exitCode = 1
continue
}

const betterId = replacements[id]
const regexEscapedId = escapeRegex(id)
// If the better id accesses a namespace, the existing `Foo as Foo$1`
// named import cannot be replaced with `Foo as Namespace.Foo`, so we
// pre-emptively remove the whole named import
if (betterId.includes('.')) {
code = code.replace(
new RegExp(`\\b\\w+\\b as ${regexEscapedId},?\\s?`),
'',
)
}
code = code.replace(
new RegExp(`\\b${regexEscapedId}\\b`, 'g'),
betterId,
)
}
}
const unreplacedIds = unique(
Array.from(code.matchAll(identifierWithTrailingDollarRE), (m) => m[0]),
)
if (unreplacedIds.length) {
const unreplacedStr = unreplacedIds.map((id) => `\n- ${id}`).join('')
this.warn(
`${chunk.fileName} contains confusing identifier names${unreplacedStr}`,
)
process.exitCode = 1
}

// Clean unnecessary comments
return code
code = code
.replace(singlelineCommentsRE, '')
.replace(multilineCommentsRE, (m) => {
return licenseCommentsRE.test(m) ? '' : m
})
.replace(consecutiveNewlinesRE, '\n\n')

return code
},
}
}

const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g
function escapeRegex(str: string): string {
return str.replace(escapeRegexRE, '\\$&')
}

function unique<T>(arr: T[]): T[] {
return Array.from(new Set(arr))
}
18 changes: 18 additions & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,24 @@ export function createHotContext(ownerPath: string): ViteHotContext {
addToMap(newListeners)
},

// remove a custom event
off(event, cb) {
const removeFromMap = (map: Map<string, any[]>) => {
const existing = map.get(event)
if (existing === undefined) {
return
}
const pruned = existing.filter((l) => l !== cb)
if (pruned.length === 0) {
map.delete(event)
return
}
map.set(event, pruned)
}
removeFromMap(customListenersMap)
removeFromMap(newListeners)
},

send(event, data) {
messageBuffer.push(JSON.stringify({ type: 'custom', event, data }))
sendMessageBuffer()
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -873,8 +873,8 @@ export function resolveBaseUrl(
logger.warn(
colors.yellow(
colors.bold(
`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
`URL, ./, or an empty string.`,
`(!) invalid "base" option: "${base}". The value can only be an absolute ` +
`URL, "./", or an empty string.`,
),
),
)
Expand Down
32 changes: 17 additions & 15 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,23 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {

css = stripBomTag(css)

// cache css compile result to map
// and then use the cache replace inline-style-flag
// when `generateBundle` in vite:build-html plugin and devHtmlHook
const inlineCSS = inlineCSSRE.test(id)
const isHTMLProxy = htmlProxyRE.test(id)
if (inlineCSS && isHTMLProxy) {
const query = parseRequest(id)
if (styleAttrRE.test(id)) {
css = css.replace(/"/g, '&quot;')
}
addToHTMLProxyTransformResult(
`${getHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
css,
)
return `export default ''`
}

const inlined = inlineRE.test(id)
const modules = cssModulesCache.get(config)!.get(id)

Expand Down Expand Up @@ -475,21 +492,6 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
// build CSS handling ----------------------------------------------------

// record css
// cache css compile result to map
// and then use the cache replace inline-style-flag when `generateBundle` in vite:build-html plugin
const inlineCSS = inlineCSSRE.test(id)
const isHTMLProxy = htmlProxyRE.test(id)
const query = parseRequest(id)
if (inlineCSS && isHTMLProxy) {
if (styleAttrRE.test(id)) {
css = css.replace(/"/g, '&quot;')
}
addToHTMLProxyTransformResult(
`${getHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
css,
)
return `export default ''`
}
if (!inlined) {
styles.set(id, css)
}
Expand Down
Loading

0 comments on commit a3f7035

Please sign in to comment.