Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: share code with vite runtime #15907

Merged
merged 13 commits into from Feb 24, 2024
1 change: 1 addition & 0 deletions .eslintrc.cjs
Expand Up @@ -145,6 +145,7 @@ module.exports = defineConfig({
},
{
files: ['packages/vite/src/node/**'],
excludedFiles: '**/__tests__/**',
rules: {
'no-console': ['error'],
},
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
@@ -1,4 +1,5 @@
packages/*/CHANGELOG.md
packages/vite/src/node/ssr/runtime/__tests__/fixtures
playground-temp/
dist/
temp/
Expand Down
1 change: 1 addition & 0 deletions packages/vite/package.json
Expand Up @@ -140,6 +140,7 @@
"postcss-modules": "^6.0.0",
"resolve.exports": "^2.0.2",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-esbuild": "^6.1.1",
"rollup-plugin-license": "^3.2.0",
"sirv": "^2.0.4",
"source-map-support": "^0.5.21",
Expand Down
49 changes: 48 additions & 1 deletion packages/vite/rollup.config.ts
Expand Up @@ -8,6 +8,7 @@ import json from '@rollup/plugin-json'
import MagicString from 'magic-string'
import type { Plugin, RollupOptions } from 'rollup'
import { defineConfig } from 'rollup'
import { minify as esbuildMinifyPlugin } from 'rollup-plugin-esbuild'
import licensePlugin from './rollupLicensePlugin'

const pkg = JSON.parse(
Expand Down Expand Up @@ -153,13 +154,13 @@ function createNodeConfig(isProduction: boolean) {
index: path.resolve(__dirname, 'src/node/index.ts'),
cli: path.resolve(__dirname, 'src/node/cli.ts'),
constants: path.resolve(__dirname, 'src/node/constants.ts'),
runtime: path.resolve(__dirname, 'src/node/ssr/runtime/index.ts'),
},
output: {
...sharedNodeOptions.output,
sourcemap: !isProduction,
},
external: [
/^vite\//,
'fsevents',
'lightningcss',
'rollup/parseAst',
Expand All @@ -176,6 +177,51 @@ function createNodeConfig(isProduction: boolean) {
})
}

function createRuntimeConfig(isProduction: boolean) {
return defineConfig({
...sharedNodeOptions,
input: {
runtime: path.resolve(__dirname, 'src/runtime/index.ts'),
},
output: {
...sharedNodeOptions.output,
sourcemap: !isProduction,
},
external: [
'fsevents',
'lightningcss',
'rollup/parseAst',
...Object.keys(pkg.dependencies),
],
plugins: [
...createNodePlugins(
false,
!isProduction,
// in production we use rollup.dts.config.ts for dts generation
// in development we need to rely on the rollup ts plugin
isProduction ? false : './dist/node',
),
esbuildMinifyPlugin({ minify: false, minifySyntax: true }),
{
name: 'replace bias',
transform(code, id) {
if (id.includes('@jridgewell+trace-mapping')) {
return {
code: code.replaceAll(
'bias === LEAST_UPPER_BOUND',
'true' +
`/*${'bias === LEAST_UPPER_BOUND'.length - '/**/'.length - 'true'.length}*/`,
),
map: null,
}
}
},
},
bundleSizeLimit(45),
],
})
}

function createCjsConfig(isProduction: boolean) {
return defineConfig({
...sharedNodeOptions,
Expand Down Expand Up @@ -209,6 +255,7 @@ export default (commandLineArgs: any): RollupOptions[] => {
envConfig,
clientConfig,
createNodeConfig(isProduction),
createRuntimeConfig(isProduction),
createCjsConfig(isProduction),
])
}
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/rollup.dts.config.ts
Expand Up @@ -15,6 +15,7 @@ const pkg = JSON.parse(

const external = [
/^node:*/,
/^vite\//,
'rollup/parseAst',
...Object.keys(pkg.dependencies),
// lightningcss types are bundled
Expand All @@ -24,7 +25,7 @@ const external = [
export default defineConfig({
input: {
index: './temp/node/index.d.ts',
runtime: './temp/node/ssr/runtime/index.d.ts',
runtime: './temp/runtime/index.d.ts',
},
output: {
dir: './dist/node',
Expand Down Expand Up @@ -132,6 +133,7 @@ function validateChunkImports(this: PluginContext, chunk: RenderedChunk) {
!id.startsWith('../') &&
!id.startsWith('node:') &&
!id.startsWith('types.d') &&
!id.startsWith('vite/') &&
!deps.includes(id) &&
!deps.some((name) => id.startsWith(name + '/'))
) {
Expand Down
Expand Up @@ -2,7 +2,8 @@ import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { transformDynamicImport } from '../../../plugins/dynamicImportVars'
import { isWindows, normalizePath } from '../../../utils'
import { normalizePath } from '../../../utils'
import { isWindows } from '../../../../shared/utils'

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

Expand Down
8 changes: 8 additions & 0 deletions packages/vite/src/node/__tests__/tsconfig.json
@@ -0,0 +1,8 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"esModuleInterop": true,
"declaration": false,
"resolveJsonModule": true
}
}
2 changes: 1 addition & 1 deletion packages/vite/src/node/__tests__/utils.spec.ts
Expand Up @@ -10,11 +10,11 @@ import {
getLocalhostAddressIfDiffersFromDNS,
injectQuery,
isFileReadable,
isWindows,
posToNumber,
processSrcSetSync,
resolveHostname,
} from '../utils'
import { isWindows } from '../../shared/utils'

describe('bareImportRE', () => {
test('should work with normal package name', () => {
Expand Down
12 changes: 6 additions & 6 deletions packages/vite/src/node/build.ts
Expand Up @@ -21,6 +21,12 @@ import commonjsPlugin from '@rollup/plugin-commonjs'
import type { RollupCommonJSOptions } from 'dep-types/commonjs'
import type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'
import type { TransformOptions } from 'esbuild'
import { withTrailingSlash } from '../shared/utils'
import {
DEFAULT_ASSETS_INLINE_LIMIT,
ESBUILD_MODULES_TARGET,
VERSION,
} from './constants'
import type { InlineConfig, ResolvedConfig } from './config'
import { resolveConfig } from './config'
import { buildReporterPlugin } from './plugins/reporter'
Expand All @@ -35,7 +41,6 @@ import {
joinUrlSegments,
normalizePath,
requireResolveFromRootWithFallback,
withTrailingSlash,
} from './utils'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
Expand All @@ -45,11 +50,6 @@ import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
import { loadFallbackPlugin } from './plugins/loadFallback'
import { findNearestPackageData } from './packages'
import type { PackageCache } from './packages'
import {
DEFAULT_ASSETS_INLINE_LIMIT,
ESBUILD_MODULES_TARGET,
VERSION,
} from './constants'
import { resolveChokidarOptions } from './watch'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/cli.ts
Expand Up @@ -3,12 +3,12 @@ import fs from 'node:fs'
import { performance } from 'node:perf_hooks'
import { cac } from 'cac'
import colors from 'picocolors'
import { VERSION } from './constants'
import type { BuildOptions } from './build'
import type { ServerOptions } from './server'
import type { CLIShortcut } from './shortcuts'
import type { LogLevel } from './logger'
import { createLogger } from './logger'
import { VERSION } from './constants'
import { resolveConfig } from './config'

const cli = cac('vite')
Expand Down
20 changes: 10 additions & 10 deletions packages/vite/src/node/config.ts
Expand Up @@ -10,6 +10,16 @@ import type { Alias, AliasOptions } from 'dep-types/alias'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import type { RollupOptions } from 'rollup'
import { withTrailingSlash } from '../shared/utils'
import {
CLIENT_ENTRY,
DEFAULT_ASSETS_RE,
DEFAULT_CONFIG_FILES,
DEFAULT_EXTENSIONS,
DEFAULT_MAIN_FIELDS,
ENV_ENTRY,
FS_PREFIX,
} from './constants'
import type { HookHandler, Plugin, PluginWithRequiredHook } from './plugin'
import type {
BuildOptions,
Expand Down Expand Up @@ -39,7 +49,6 @@ import {
mergeConfig,
normalizeAlias,
normalizePath,
withTrailingSlash,
} from './utils'
import { getFsUtils } from './fsUtils'
import {
Expand All @@ -49,15 +58,6 @@ import {
resolvePlugins,
} from './plugins'
import type { ESBuildOptions } from './plugins/esbuild'
import {
CLIENT_ENTRY,
DEFAULT_ASSETS_RE,
DEFAULT_CONFIG_FILES,
DEFAULT_EXTENSIONS,
DEFAULT_MAIN_FIELDS,
ENV_ENTRY,
FS_PREFIX,
} from './constants'
import type { InternalResolveOptions, ResolveOptions } from './plugins/resolve'
import { resolvePlugin, tryNodeResolve } from './plugins/resolve'
import type { LogLevel, Logger } from './logger'
Expand Down
18 changes: 0 additions & 18 deletions packages/vite/src/node/constants.ts
Expand Up @@ -59,24 +59,6 @@ export const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
*/
export const FS_PREFIX = `/@fs/`

/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
export const VALID_ID_PREFIX = `/@id/`

/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
export const NULL_BYTE_PLACEHOLDER = `__x00__`

export const CLIENT_PUBLIC_PATH = `/@vite/client`
export const ENV_PUBLIC_PATH = `/@vite/env`
export const VITE_PACKAGE_DIR = resolve(
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/index.ts
Expand Up @@ -128,10 +128,10 @@ export type {
HMRBroadcasterClient,
} from './server/hmr'

export type { FetchFunction } from './ssr/runtime/index'
export { createViteRuntime } from './ssr/runtime/node/mainThreadRuntime'
export type { MainThreadRuntimeOptions } from './ssr/runtime/node/mainThreadRuntime'
export { ServerHMRConnector } from './ssr/runtime/node/serverHmrConnector'
export type { FetchFunction } from '../runtime/index'
export { createViteRuntime } from './ssr/runtime/mainThreadRuntime'
export type { MainThreadRuntimeOptions } from './ssr/runtime/mainThreadRuntime'
export { ServerHMRConnector } from './ssr/runtime/serverHmrConnector'

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

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/index.ts
Expand Up @@ -15,7 +15,6 @@ import {
flattenId,
getHash,
isOptimizable,
isWindows,
lookupFile,
normalizeId,
normalizePath,
Expand All @@ -25,6 +24,7 @@ import {
} from '../utils'
import { transformWithEsbuild } from '../plugins/esbuild'
import { ESBUILD_MODULES_TARGET, METADATA_FILENAME } from '../constants'
import { isWindows } from '../../shared/utils'
import { esbuildCjsExternalPlugin, esbuildDepPlugin } from './esbuildDepPlugin'
import { scanImports } from './scan'
import { createOptimizeDepsIncludeResolver, expandGlobIds } from './resolve'
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/optimizer/resolve.ts
Expand Up @@ -2,8 +2,9 @@ import path from 'node:path'
import glob from 'fast-glob'
import micromatch from 'micromatch'
import type { ResolvedConfig } from '../config'
import { escapeRegex, getNpmPackageName, slash } from '../utils'
import { escapeRegex, getNpmPackageName } from '../utils'
import { resolvePackageData } from '../packages'
import { slash } from '../../shared/utils'

export function createOptimizeDepsIncludeResolver(
config: ResolvedConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/scan.ts
Expand Up @@ -21,7 +21,6 @@ import {
} from '../constants'
import {
arraify,
cleanUrl,
createDebugger,
dataUrlRE,
externalRE,
Expand All @@ -38,6 +37,7 @@ import {
import type { PluginContainer } from '../server/pluginContainer'
import { createPluginContainer } from '../server/pluginContainer'
import { transformGlobImport } from '../plugins/importMetaGlob'
import { cleanUrl } from '../../shared/utils'
import { loadTsconfigJsonForFile } from '../plugins/esbuild'

type ResolveIdOptions = Parameters<PluginContainer['resolveId']>[2]
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/plugins/asset.ts
Expand Up @@ -18,7 +18,6 @@ import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
import { checkPublicFile } from '../publicDir'
import {
cleanUrl,
getHash,
injectQuery,
joinUrlSegments,
Expand All @@ -27,10 +26,10 @@ import {
removeLeadingSlash,
removeUrlQuery,
urlRE,
withTrailingSlash,
} from '../utils'
import { DEFAULT_ASSETS_INLINE_LIMIT, FS_PREFIX } from '../constants'
import type { ModuleGraph } from '../server/moduleGraph'
import { cleanUrl, withTrailingSlash } from '../../shared/utils'

// referenceId is base64url but replaces - with $
export const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g
Expand Down
8 changes: 2 additions & 6 deletions packages/vite/src/node/plugins/assetImportMetaUrl.ts
Expand Up @@ -4,13 +4,9 @@ import { stripLiteral } from 'strip-literal'
import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
import type { ResolveFn } from '../'
import {
injectQuery,
isParentDirectory,
slash,
transformStableResult,
} from '../utils'
import { injectQuery, isParentDirectory, transformStableResult } from '../utils'
import { CLIENT_ENTRY } from '../constants'
import { slash } from '../../shared/utils'
import { fileToUrl } from './asset'
import { preloadHelperId } from './importAnalysisBuild'
import type { InternalResolveOptions } from './resolve'
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -46,7 +46,6 @@ import { checkPublicFile } from '../publicDir'
import {
arraify,
asyncReplace,
cleanUrl,
combineSourcemaps,
createSerialPromiseQueue,
emptyCssComments,
Expand All @@ -63,12 +62,12 @@ import {
removeDirectQuery,
removeUrlQuery,
requireResolveFromRootWithFallback,
slash,
stripBase,
stripBomTag,
urlRE,
} from '../utils'
import type { Logger } from '../logger'
import { cleanUrl, slash } from '../../shared/utils'
import { addToHTMLProxyTransformResult } from './html'
import {
assetUrlRE,
Expand Down