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

WIP: feat: Node ESM loader #9740

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/plugin-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
}
},
async transform(code, id, options) {
const ssr = options?.ssr === true
const ssr = !!options?.ssr
// File extension could be mocked/overridden in querystring.
const [filepath, querystring = ''] = id.split('?')
const [extension = ''] =
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"types": "./client.d.ts"
},
"./dist/client/*": "./dist/client/*",
"./package.json": "./package.json"
"./package.json": "./package.json",
"./loader": "./dist/node/loader.js"
},
"files": [
"bin",
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ function createNodeConfig(isProduction: boolean) {
input: {
index: path.resolve(__dirname, 'src/node/index.ts'),
cli: path.resolve(__dirname, 'src/node/cli.ts'),
constants: path.resolve(__dirname, 'src/node/constants.ts')
constants: path.resolve(__dirname, 'src/node/constants.ts'),
loader: path.resolve(__dirname, 'src/node/ssr/loader.ts')
},
output: {
...sharedNodeOptions.output,
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export async function initDepsOptimizer(
): Promise<void> {
// Non Dev SSR Optimizer
const ssr = config.command === 'build' && !!config.build.ssr
if (!getDepsOptimizer(config, ssr)) {
if (!getDepsOptimizer(config, !!ssr)) {
await createDepsOptimizer(config, server)
}
}
Expand All @@ -78,10 +78,10 @@ export async function initDevSsrDepsOptimizer(
// If ssrLoadModule is called before server.listen(), the main deps optimizer
// will not be yet created
const ssr = false
if (!getDepsOptimizer(config, ssr)) {
if (!getDepsOptimizer(config, !!ssr)) {
await initDepsOptimizer(config, server)
}
await getDepsOptimizer(config, ssr)!.scanProcessing
await getDepsOptimizer(config, !!ssr)!.scanProcessing

await createDevSsrDepsOptimizer(config)
creatingDevSsrOptimizer = undefined
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export interface Plugin extends RollupPlugin {
importer: string | undefined,
options: {
custom?: CustomPluginOptions
ssr?: boolean
ssr?: boolean | 'loader'
/**
* @internal
*/
Expand All @@ -151,6 +151,6 @@ export interface Plugin extends RollupPlugin {
this: TransformPluginContext,
code: string,
id: string,
options?: { ssr?: boolean }
options?: { ssr?: boolean | 'loader' }
) => Promise<TransformResult> | TransformResult
}
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
) {
return
}
const ssr = options?.ssr === true
const ssr = options?.ssr || false

const urlReplacer: CssUrlReplacer = async (url, importer) => {
if (checkPublicFile(url, config)) {
Expand Down Expand Up @@ -259,7 +259,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
(
await fileToUrl(file, config, this)
).replace((config.server?.origin ?? '') + devBase, '/'),
ssr
!!ssr
)
)
}
Expand All @@ -272,7 +272,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
new Set(),
null,
isSelfAccepting,
ssr
!!ssr
)
for (const file of deps) {
this.addWatchFile(file)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export function definePlugin(config: ResolvedConfig): Plugin {
name: 'vite:define',

transform(code, id, options) {
const ssr = options?.ssr === true
const ssr = options?.ssr || false
if (!ssr && !isBuild) {
// for dev we inject actual global defines in the vite client to
// avoid the transform cost.
Expand Down
12 changes: 6 additions & 6 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
return null
}

const ssr = options?.ssr === true
const ssr = options?.ssr || false
const prettyImporter = prettifyUrl(importer, root)

if (canSkipImportAnalysis(importer)) {
Expand Down Expand Up @@ -215,7 +215,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

const depsOptimizer = getDepsOptimizer(config, ssr)
const depsOptimizer = getDepsOptimizer(config, !!ssr)

const { moduleGraph } = server
// since we are already in the transform phase of the importer, it must
Expand Down Expand Up @@ -269,7 +269,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {

let importerFile = importer

const optimizeDeps = getDepOptimizationConfig(config, ssr)
const optimizeDeps = getDepOptimizationConfig(config, !!ssr)
if (moduleListContains(optimizeDeps?.exclude, url)) {
if (depsOptimizer) {
await depsOptimizer.scanProcessing
Expand Down Expand Up @@ -496,7 +496,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
depsOptimizer.metadata,
file,
config,
ssr
!!ssr
)

if (needsInterop === undefined) {
Expand Down Expand Up @@ -641,7 +641,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
for (const { url, start, end } of acceptedUrls) {
const [normalized] = await moduleGraph.resolveUrl(
toAbsoluteUrl(markExplicitImport(url)),
ssr
!!ssr
)
normalizedAcceptedUrls.add(normalized)
str().overwrite(start, end, JSON.stringify(normalized), {
Expand Down Expand Up @@ -687,7 +687,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
normalizedAcceptedUrls,
isPartiallySelfAccepting ? acceptedExports : null,
isSelfAccepting,
ssr
!!ssr
)
if (hasHMR && prunedImports) {
handlePrunedModules(prunedImports, server)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
}

const { root } = config
const depsOptimizer = getDepsOptimizer(config, ssr)
const depsOptimizer = getDepsOptimizer(config, !!ssr)

const normalizeUrl = async (
url: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export async function resolvePlugins(
packageCache: config.packageCache,
ssrConfig: config.ssr,
asSrc: true,
getDepsOptimizer: (ssr: boolean) => getDepsOptimizer(config, ssr),
getDepsOptimizer: (ssr: boolean) => getDepsOptimizer(config, !!ssr),
shouldExternalize:
isBuild && config.build.ssr && config.ssr?.format !== 'cjs'
? (id) => shouldExternalizeForSSR(id, config)
Expand Down
16 changes: 8 additions & 8 deletions packages/vite/src/node/plugins/optimizedDeps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function optimizedDepsPlugin(config: ResolvedConfig): Plugin {
name: 'vite:optimized-deps',

async resolveId(id, source, { ssr }) {
if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
if (getDepsOptimizer(config, !!ssr)?.isOptimizedDepFile(id)) {
return id
}
},
Expand All @@ -28,8 +28,8 @@ export function optimizedDepsPlugin(config: ResolvedConfig): Plugin {
// is in importAnalysis, see call to delayDepsOptimizerUntil

async load(id, options) {
const ssr = options?.ssr === true
const depsOptimizer = getDepsOptimizer(config, ssr)
const ssr = options?.ssr || false
const depsOptimizer = getDepsOptimizer(config, !!ssr)
if (depsOptimizer?.isOptimizedDepFile(id)) {
const metadata = depsOptimizer.metadata
const file = cleanUrl(id)
Expand Down Expand Up @@ -90,21 +90,21 @@ export function optimizedDepsBuildPlugin(config: ResolvedConfig): Plugin {
},

async resolveId(id, importer, { ssr }) {
if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
if (getDepsOptimizer(config, !!ssr)?.isOptimizedDepFile(id)) {
return id
}
},

transform(_code, id, options) {
const ssr = options?.ssr === true
getDepsOptimizer(config, ssr)?.delayDepsOptimizerUntil(id, async () => {
const ssr = options?.ssr || false
getDepsOptimizer(config, !!ssr)?.delayDepsOptimizerUntil(id, async () => {
await this.load({ id })
})
},

async load(id, options) {
const ssr = options?.ssr === true
const depsOptimizer = getDepsOptimizer(config, ssr)
const ssr = options?.ssr || false
const depsOptimizer = getDepsOptimizer(config, !!ssr)
if (!depsOptimizer?.isOptimizedDepFile(id)) {
return
}
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/preAlias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export function preAliasPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:pre-alias',
async resolveId(id, importer, options) {
const ssr = options?.ssr === true
const depsOptimizer = getDepsOptimizer(config, ssr)
const ssr = options?.ssr || false
const depsOptimizer = getDepsOptimizer(config, !!ssr)
if (
importer &&
depsOptimizer &&
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
},

async transform(raw, id, options) {
const ssr = options?.ssr === true
const ssr = options?.ssr || false
const query = parseRequest(id)
if (query && query[WORKER_FILE_ID] != null) {
// if import worker by worker constructor will had query.type
Expand Down Expand Up @@ -261,7 +261,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
: 'module'
const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}'
if (isBuild) {
getDepsOptimizer(config, ssr)?.registerWorkersSource(id)
getDepsOptimizer(config, !!ssr)?.registerWorkersSource(id)
if (query.inline != null) {
const chunk = await bundleWorkerEntry(config, id, query)
// inline as blob data url
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
name: 'vite:worker-import-meta-url',

async transform(code, id, options) {
const ssr = options?.ssr === true
const ssr = options?.ssr || false
if (
!options?.ssr &&
(code.includes('new Worker') || code.includes('new SharedWorker')) &&
Expand Down Expand Up @@ -118,7 +118,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {

let url: string
if (isBuild) {
getDepsOptimizer(config, ssr)?.registerWorkersSource(id)
getDepsOptimizer(config, !!ssr)?.registerWorkersSource(id)
url = await workerFileToUrl(config, file, query)
} else {
url = await fileToUrl(cleanUrl(file), config, this)
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/server/pluginContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export interface PluginContainer {
options?: {
custom?: CustomPluginOptions
skip?: Set<Plugin>
ssr?: boolean
ssr?: boolean | 'loader'
/**
* @internal
*/
Expand All @@ -107,7 +107,7 @@ export interface PluginContainer {
id: string,
options?: {
inMap?: SourceDescription['map']
ssr?: boolean
ssr?: boolean | 'loader'
}
): Promise<SourceDescription | null>
load(
Expand Down Expand Up @@ -236,7 +236,7 @@ export async function createPluginContainer(
// using a class to make creating new contexts more efficient
class Context implements PluginContext {
meta = minimalContext.meta
ssr = false
ssr: boolean | 'loader' = false
_scan = false
_activePlugin: Plugin | null
_activeId: string | null = null
Expand Down Expand Up @@ -537,7 +537,7 @@ export async function createPluginContainer(
const ssr = options?.ssr
const scan = !!options?.scan
const ctx = new Context()
ctx.ssr = !!ssr
ctx.ssr = ssr || false
ctx._scan = scan
ctx._resolveSkips = skip
const resolveStart = isDebug ? performance.now() : 0
Expand Down
23 changes: 11 additions & 12 deletions packages/vite/src/node/server/transformRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface TransformResult {
}

export interface TransformOptions {
ssr?: boolean
ssr?: boolean | 'loader'
html?: boolean
}

Expand Down Expand Up @@ -71,7 +71,7 @@ export function transformRequest(
const pending = server._pendingRequests.get(cacheKey)
if (pending) {
return server.moduleGraph
.getModuleByUrl(removeTimestampQuery(url), options.ssr)
.getModuleByUrl(removeTimestampQuery(url), !!options.ssr)
.then((module) => {
if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
// The pending request is still valid, we can safely reuse its result
Expand Down Expand Up @@ -141,11 +141,13 @@ async function doTransform(

// resolve
const id =
(await pluginContainer.resolveId(url, undefined, { ssr }))?.id || url
options.ssr === 'loader'
? url
: (await pluginContainer.resolveId(url, undefined, { ssr }))?.id || url

const result = loadAndTransform(id, url, server, options, timestamp)

getDepsOptimizer(config, ssr)?.delayDepsOptimizerUntil(id, () => result)
getDepsOptimizer(config, !!ssr)?.delayDepsOptimizerUntil(id, () => result)

return result
}
Expand Down Expand Up @@ -233,7 +235,7 @@ async function loadAndTransform(
const transformStart = isDebug ? performance.now() : 0
const transformResult = await pluginContainer.transform(code, id, {
inMap: map,
ssr
ssr: options.ssr
})
const originalCode = code
if (
Expand All @@ -259,13 +261,10 @@ async function loadAndTransform(
}

const result = ssr
? await ssrTransform(
code,
map as SourceMap,
url,
originalCode,
server.config
)
? await ssrTransform(code, map as SourceMap, url, originalCode, {
json: server.config.json,
loader: options.ssr === 'loader'
})
: ({
code,
map,
Expand Down
Loading