Skip to content

Commit b20d542

Browse files
authored
refactor: share code with vite runtime (#15907)
1 parent 42fd11c commit b20d542

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+372
-553
lines changed

.eslintrc.cjs

+1
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ module.exports = defineConfig({
145145
},
146146
{
147147
files: ['packages/vite/src/node/**'],
148+
excludedFiles: '**/__tests__/**',
148149
rules: {
149150
'no-console': ['error'],
150151
},

.prettierignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
packages/*/CHANGELOG.md
2+
packages/vite/src/node/ssr/runtime/__tests__/fixtures
23
playground-temp/
34
dist/
45
temp/

packages/vite/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@
140140
"postcss-modules": "^6.0.0",
141141
"resolve.exports": "^2.0.2",
142142
"rollup-plugin-dts": "^6.1.0",
143+
"rollup-plugin-esbuild": "^6.1.1",
143144
"rollup-plugin-license": "^3.2.0",
144145
"sirv": "^2.0.4",
145146
"source-map-support": "^0.5.21",

packages/vite/rollup.config.ts

+48-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import json from '@rollup/plugin-json'
88
import MagicString from 'magic-string'
99
import type { Plugin, RollupOptions } from 'rollup'
1010
import { defineConfig } from 'rollup'
11+
import { minify as esbuildMinifyPlugin } from 'rollup-plugin-esbuild'
1112
import licensePlugin from './rollupLicensePlugin'
1213

1314
const pkg = JSON.parse(
@@ -153,13 +154,13 @@ function createNodeConfig(isProduction: boolean) {
153154
index: path.resolve(__dirname, 'src/node/index.ts'),
154155
cli: path.resolve(__dirname, 'src/node/cli.ts'),
155156
constants: path.resolve(__dirname, 'src/node/constants.ts'),
156-
runtime: path.resolve(__dirname, 'src/node/ssr/runtime/index.ts'),
157157
},
158158
output: {
159159
...sharedNodeOptions.output,
160160
sourcemap: !isProduction,
161161
},
162162
external: [
163+
/^vite\//,
163164
'fsevents',
164165
'lightningcss',
165166
'rollup/parseAst',
@@ -176,6 +177,51 @@ function createNodeConfig(isProduction: boolean) {
176177
})
177178
}
178179

180+
function createRuntimeConfig(isProduction: boolean) {
181+
return defineConfig({
182+
...sharedNodeOptions,
183+
input: {
184+
runtime: path.resolve(__dirname, 'src/runtime/index.ts'),
185+
},
186+
output: {
187+
...sharedNodeOptions.output,
188+
sourcemap: !isProduction,
189+
},
190+
external: [
191+
'fsevents',
192+
'lightningcss',
193+
'rollup/parseAst',
194+
...Object.keys(pkg.dependencies),
195+
],
196+
plugins: [
197+
...createNodePlugins(
198+
false,
199+
!isProduction,
200+
// in production we use rollup.dts.config.ts for dts generation
201+
// in development we need to rely on the rollup ts plugin
202+
isProduction ? false : './dist/node',
203+
),
204+
esbuildMinifyPlugin({ minify: false, minifySyntax: true }),
205+
{
206+
name: 'replace bias',
207+
transform(code, id) {
208+
if (id.includes('@jridgewell+trace-mapping')) {
209+
return {
210+
code: code.replaceAll(
211+
'bias === LEAST_UPPER_BOUND',
212+
'true' +
213+
`/*${'bias === LEAST_UPPER_BOUND'.length - '/**/'.length - 'true'.length}*/`,
214+
),
215+
map: null,
216+
}
217+
}
218+
},
219+
},
220+
bundleSizeLimit(45),
221+
],
222+
})
223+
}
224+
179225
function createCjsConfig(isProduction: boolean) {
180226
return defineConfig({
181227
...sharedNodeOptions,
@@ -209,6 +255,7 @@ export default (commandLineArgs: any): RollupOptions[] => {
209255
envConfig,
210256
clientConfig,
211257
createNodeConfig(isProduction),
258+
createRuntimeConfig(isProduction),
212259
createCjsConfig(isProduction),
213260
])
214261
}

packages/vite/rollup.dts.config.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const pkg = JSON.parse(
1515

1616
const external = [
1717
/^node:*/,
18+
/^vite\//,
1819
'rollup/parseAst',
1920
...Object.keys(pkg.dependencies),
2021
// lightningcss types are bundled
@@ -24,7 +25,7 @@ const external = [
2425
export default defineConfig({
2526
input: {
2627
index: './temp/node/index.d.ts',
27-
runtime: './temp/node/ssr/runtime/index.d.ts',
28+
runtime: './temp/runtime/index.d.ts',
2829
},
2930
output: {
3031
dir: './dist/node',
@@ -132,6 +133,7 @@ function validateChunkImports(this: PluginContext, chunk: RenderedChunk) {
132133
!id.startsWith('../') &&
133134
!id.startsWith('node:') &&
134135
!id.startsWith('types.d') &&
136+
!id.startsWith('vite/') &&
135137
!deps.includes(id) &&
136138
!deps.some((name) => id.startsWith(name + '/'))
137139
) {

packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.spec.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import { resolve } from 'node:path'
22
import { fileURLToPath } from 'node:url'
33
import { describe, expect, it } from 'vitest'
44
import { transformDynamicImport } from '../../../plugins/dynamicImportVars'
5-
import { isWindows, normalizePath } from '../../../utils'
5+
import { normalizePath } from '../../../utils'
6+
import { isWindows } from '../../../../shared/utils'
67

78
const __dirname = resolve(fileURLToPath(import.meta.url), '..')
89

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"extends": "../../../tsconfig.base.json",
3+
"compilerOptions": {
4+
"esModuleInterop": true,
5+
"declaration": false,
6+
"resolveJsonModule": true
7+
}
8+
}

packages/vite/src/node/__tests__/utils.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ import {
1010
getLocalhostAddressIfDiffersFromDNS,
1111
injectQuery,
1212
isFileReadable,
13-
isWindows,
1413
posToNumber,
1514
processSrcSetSync,
1615
resolveHostname,
1716
} from '../utils'
17+
import { isWindows } from '../../shared/utils'
1818

1919
describe('bareImportRE', () => {
2020
test('should work with normal package name', () => {

packages/vite/src/node/build.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ import commonjsPlugin from '@rollup/plugin-commonjs'
2121
import type { RollupCommonJSOptions } from 'dep-types/commonjs'
2222
import type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'
2323
import type { TransformOptions } from 'esbuild'
24+
import { withTrailingSlash } from '../shared/utils'
25+
import {
26+
DEFAULT_ASSETS_INLINE_LIMIT,
27+
ESBUILD_MODULES_TARGET,
28+
VERSION,
29+
} from './constants'
2430
import type { InlineConfig, ResolvedConfig } from './config'
2531
import { resolveConfig } from './config'
2632
import { buildReporterPlugin } from './plugins/reporter'
@@ -35,7 +41,6 @@ import {
3541
joinUrlSegments,
3642
normalizePath,
3743
requireResolveFromRootWithFallback,
38-
withTrailingSlash,
3944
} from './utils'
4045
import { manifestPlugin } from './plugins/manifest'
4146
import type { Logger } from './logger'
@@ -45,11 +50,6 @@ import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
4550
import { loadFallbackPlugin } from './plugins/loadFallback'
4651
import { findNearestPackageData } from './packages'
4752
import type { PackageCache } from './packages'
48-
import {
49-
DEFAULT_ASSETS_INLINE_LIMIT,
50-
ESBUILD_MODULES_TARGET,
51-
VERSION,
52-
} from './constants'
5353
import { resolveChokidarOptions } from './watch'
5454
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
5555
import { mergeConfig } from './publicUtils'

packages/vite/src/node/cli.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ import fs from 'node:fs'
33
import { performance } from 'node:perf_hooks'
44
import { cac } from 'cac'
55
import colors from 'picocolors'
6+
import { VERSION } from './constants'
67
import type { BuildOptions } from './build'
78
import type { ServerOptions } from './server'
89
import type { CLIShortcut } from './shortcuts'
910
import type { LogLevel } from './logger'
1011
import { createLogger } from './logger'
11-
import { VERSION } from './constants'
1212
import { resolveConfig } from './config'
1313

1414
const cli = cac('vite')

packages/vite/src/node/config.ts

+10-10
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ import type { Alias, AliasOptions } from 'dep-types/alias'
1010
import aliasPlugin from '@rollup/plugin-alias'
1111
import { build } from 'esbuild'
1212
import type { RollupOptions } from 'rollup'
13+
import { withTrailingSlash } from '../shared/utils'
14+
import {
15+
CLIENT_ENTRY,
16+
DEFAULT_ASSETS_RE,
17+
DEFAULT_CONFIG_FILES,
18+
DEFAULT_EXTENSIONS,
19+
DEFAULT_MAIN_FIELDS,
20+
ENV_ENTRY,
21+
FS_PREFIX,
22+
} from './constants'
1323
import type { HookHandler, Plugin, PluginWithRequiredHook } from './plugin'
1424
import type {
1525
BuildOptions,
@@ -39,7 +49,6 @@ import {
3949
mergeConfig,
4050
normalizeAlias,
4151
normalizePath,
42-
withTrailingSlash,
4352
} from './utils'
4453
import { getFsUtils } from './fsUtils'
4554
import {
@@ -49,15 +58,6 @@ import {
4958
resolvePlugins,
5059
} from './plugins'
5160
import type { ESBuildOptions } from './plugins/esbuild'
52-
import {
53-
CLIENT_ENTRY,
54-
DEFAULT_ASSETS_RE,
55-
DEFAULT_CONFIG_FILES,
56-
DEFAULT_EXTENSIONS,
57-
DEFAULT_MAIN_FIELDS,
58-
ENV_ENTRY,
59-
FS_PREFIX,
60-
} from './constants'
6161
import type { InternalResolveOptions, ResolveOptions } from './plugins/resolve'
6262
import { resolvePlugin, tryNodeResolve } from './plugins/resolve'
6363
import type { LogLevel, Logger } from './logger'

packages/vite/src/node/constants.ts

-18
Original file line numberDiff line numberDiff line change
@@ -59,24 +59,6 @@ export const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
5959
*/
6060
export const FS_PREFIX = `/@fs/`
6161

62-
/**
63-
* Prefix for resolved Ids that are not valid browser import specifiers
64-
*/
65-
export const VALID_ID_PREFIX = `/@id/`
66-
67-
/**
68-
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
69-
* module ID with `\0`, a convention from the rollup ecosystem.
70-
* This prevents other plugins from trying to process the id (like node resolution),
71-
* and core features like sourcemaps can use this info to differentiate between
72-
* virtual modules and regular files.
73-
* `\0` is not a permitted char in import URLs so we have to replace them during
74-
* import analysis. The id will be decoded back before entering the plugins pipeline.
75-
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
76-
* modules in the browser end up encoded as `/@id/__x00__{id}`
77-
*/
78-
export const NULL_BYTE_PLACEHOLDER = `__x00__`
79-
8062
export const CLIENT_PUBLIC_PATH = `/@vite/client`
8163
export const ENV_PUBLIC_PATH = `/@vite/env`
8264
export const VITE_PACKAGE_DIR = resolve(

packages/vite/src/node/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,10 @@ export type {
128128
HMRBroadcasterClient,
129129
} from './server/hmr'
130130

131-
export type { FetchFunction } from './ssr/runtime/index'
132-
export { createViteRuntime } from './ssr/runtime/node/mainThreadRuntime'
133-
export type { MainThreadRuntimeOptions } from './ssr/runtime/node/mainThreadRuntime'
134-
export { ServerHMRConnector } from './ssr/runtime/node/serverHmrConnector'
131+
export type { FetchFunction } from '../runtime/index'
132+
export { createViteRuntime } from './ssr/runtime/mainThreadRuntime'
133+
export type { MainThreadRuntimeOptions } from './ssr/runtime/mainThreadRuntime'
134+
export { ServerHMRConnector } from './ssr/runtime/serverHmrConnector'
135135

136136
export type { BindCLIShortcutsOptions, CLIShortcut } from './shortcuts'
137137

packages/vite/src/node/optimizer/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import {
1515
flattenId,
1616
getHash,
1717
isOptimizable,
18-
isWindows,
1918
lookupFile,
2019
normalizeId,
2120
normalizePath,
@@ -25,6 +24,7 @@ import {
2524
} from '../utils'
2625
import { transformWithEsbuild } from '../plugins/esbuild'
2726
import { ESBUILD_MODULES_TARGET, METADATA_FILENAME } from '../constants'
27+
import { isWindows } from '../../shared/utils'
2828
import { esbuildCjsExternalPlugin, esbuildDepPlugin } from './esbuildDepPlugin'
2929
import { scanImports } from './scan'
3030
import { createOptimizeDepsIncludeResolver, expandGlobIds } from './resolve'

packages/vite/src/node/optimizer/resolve.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ import path from 'node:path'
22
import glob from 'fast-glob'
33
import micromatch from 'micromatch'
44
import type { ResolvedConfig } from '../config'
5-
import { escapeRegex, getNpmPackageName, slash } from '../utils'
5+
import { escapeRegex, getNpmPackageName } from '../utils'
66
import { resolvePackageData } from '../packages'
7+
import { slash } from '../../shared/utils'
78

89
export function createOptimizeDepsIncludeResolver(
910
config: ResolvedConfig,

packages/vite/src/node/optimizer/scan.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import {
2121
} from '../constants'
2222
import {
2323
arraify,
24-
cleanUrl,
2524
createDebugger,
2625
dataUrlRE,
2726
externalRE,
@@ -38,6 +37,7 @@ import {
3837
import type { PluginContainer } from '../server/pluginContainer'
3938
import { createPluginContainer } from '../server/pluginContainer'
4039
import { transformGlobImport } from '../plugins/importMetaGlob'
40+
import { cleanUrl } from '../../shared/utils'
4141
import { loadTsconfigJsonForFile } from '../plugins/esbuild'
4242

4343
type ResolveIdOptions = Parameters<PluginContainer['resolveId']>[2]

packages/vite/src/node/plugins/asset.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import type { Plugin } from '../plugin'
1818
import type { ResolvedConfig } from '../config'
1919
import { checkPublicFile } from '../publicDir'
2020
import {
21-
cleanUrl,
2221
getHash,
2322
injectQuery,
2423
joinUrlSegments,
@@ -27,10 +26,10 @@ import {
2726
removeLeadingSlash,
2827
removeUrlQuery,
2928
urlRE,
30-
withTrailingSlash,
3129
} from '../utils'
3230
import { DEFAULT_ASSETS_INLINE_LIMIT, FS_PREFIX } from '../constants'
3331
import type { ModuleGraph } from '../server/moduleGraph'
32+
import { cleanUrl, withTrailingSlash } from '../../shared/utils'
3433

3534
// referenceId is base64url but replaces - with $
3635
export const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g

packages/vite/src/node/plugins/assetImportMetaUrl.ts

+2-6
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,9 @@ import { stripLiteral } from 'strip-literal'
44
import type { Plugin } from '../plugin'
55
import type { ResolvedConfig } from '../config'
66
import type { ResolveFn } from '../'
7-
import {
8-
injectQuery,
9-
isParentDirectory,
10-
slash,
11-
transformStableResult,
12-
} from '../utils'
7+
import { injectQuery, isParentDirectory, transformStableResult } from '../utils'
138
import { CLIENT_ENTRY } from '../constants'
9+
import { slash } from '../../shared/utils'
1410
import { fileToUrl } from './asset'
1511
import { preloadHelperId } from './importAnalysisBuild'
1612
import type { InternalResolveOptions } from './resolve'

packages/vite/src/node/plugins/css.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ import { checkPublicFile } from '../publicDir'
4646
import {
4747
arraify,
4848
asyncReplace,
49-
cleanUrl,
5049
combineSourcemaps,
5150
createSerialPromiseQueue,
5251
emptyCssComments,
@@ -63,12 +62,12 @@ import {
6362
removeDirectQuery,
6463
removeUrlQuery,
6564
requireResolveFromRootWithFallback,
66-
slash,
6765
stripBase,
6866
stripBomTag,
6967
urlRE,
7068
} from '../utils'
7169
import type { Logger } from '../logger'
70+
import { cleanUrl, slash } from '../../shared/utils'
7271
import { addToHTMLProxyTransformResult } from './html'
7372
import {
7473
assetUrlRE,

0 commit comments

Comments
 (0)