Skip to content

Commit

Permalink
fix: support cjs globals in default modules evaluator
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Nov 12, 2024
1 parent fa8f085 commit e546e04
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 60 deletions.
18 changes: 17 additions & 1 deletion packages/vite/src/module-runner/esmEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,18 @@ import {
} from './constants'
import type { ModuleEvaluator, ModuleRunnerContext } from './types'

export interface ESModulesEvaluatorOptions {
cjsGlobals?: boolean
startOffset?: number
}

export class ESModulesEvaluator implements ModuleEvaluator {
startOffset = getAsyncFunctionDeclarationPaddingLineCount()
public readonly startOffset: number

constructor(private options: ESModulesEvaluatorOptions = {}) {
this.startOffset =
options.startOffset ?? getAsyncFunctionDeclarationPaddingLineCount()
}

async runInlinedModule(
context: ModuleRunnerContext,
Expand All @@ -25,16 +35,22 @@ export class ESModulesEvaluator implements ModuleEvaluator {
ssrImportKey,
ssrDynamicImportKey,
ssrExportAllKey,
'__filename',
'__dirname',
// source map should already be inlined by Vite
'"use strict";' + code,
)

const meta = context[ssrImportMetaKey]

await initModule(
context[ssrModuleExportsKey],
context[ssrImportMetaKey],
context[ssrImportKey],
context[ssrDynamicImportKey],
context[ssrExportAllKey],
this.options.cjsGlobals ? meta.filename : undefined,
this.options.cjsGlobals ? meta.dirname : undefined,
)

Object.seal(context[ssrModuleExportsKey])
Expand Down
5 changes: 4 additions & 1 deletion packages/vite/src/module-runner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

export { EvaluatedModules, type EvaluatedModuleNode } from './evaluatedModules'
export { ModuleRunner } from './runner'
export { ESModulesEvaluator } from './esmEvaluator'
export {
ESModulesEvaluator,
type ESModulesEvaluatorOptions,
} from './esmEvaluator'

export { createWebSocketModuleRunnerTransport } from '../shared/moduleRunnerTransport'

Expand Down
129 changes: 71 additions & 58 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import colors from 'picocolors'
import type { Alias, AliasOptions } from 'dep-types/alias'
import type { RollupOptions } from 'rollup'
import picomatch from 'picomatch'
import { ESModulesEvaluator } from 'vite/module-runner'
import type { AnymatchFn } from '../types/anymatch'
import { withTrailingSlash } from '../shared/utils'
import {
Expand Down Expand Up @@ -37,7 +38,6 @@ import { resolveBuildEnvironmentOptions, resolveBuilderOptions } from './build'
import type { ResolvedServerOptions, ServerOptions } from './server'
import { resolveServerOptions } from './server'
import { DevEnvironment } from './server/environment'
import type { RunnableDevEnvironment } from './server/environments/runnableEnvironment'
import { createRunnableDevEnvironment } from './server/environments/runnableEnvironment'
import type { WebSocketServer } from './server/ws'
import type { PreviewOptions, ResolvedPreviewOptions } from './preview'
Expand Down Expand Up @@ -1529,87 +1529,100 @@ export async function loadConfigFromFile(
return null
}

let environment: RunnableDevEnvironment | undefined

try {
environment = createRunnableDevEnvironment(
'config',
await resolveConfig(
{
configFile: false,
environments: {
config: {
consumer: 'server',
dev: {
moduleRunnerTransform: true,
},
resolve: {
external: true,
},
const { userConfig, dependencies } = await importConfig(resolvedPath)
debug?.(`config file loaded in ${getTime()}`)

const config = await (typeof userConfig === 'function'
? userConfig(configEnv)
: userConfig)
if (!isObject(config)) {
throw new Error(`config must export or return an object.`)
}
return {
path: normalizePath(resolvedPath),
config,
dependencies,
}
} catch (e) {
createLogger(logLevel, { customLogger }).error(
colors.red(`failed to load config from ${resolvedPath}`),
{
error: e,
},
)
throw e
}
}

async function importConfig(resolvedPath: string) {
const environment = createRunnableDevEnvironment(
'config',
// TODO: provide a dummy config?
await resolveConfig(
{
configFile: false,
environments: {
config: {
consumer: 'server',
dev: {
moduleRunnerTransform: true,
},
resolve: {
external: true,
},
},
},
'serve',
),
{
// options: {
// consumer: 'server',
// dev: {
// moduleRunnerTransform: true,
// },
// TODO for some reason this doesn't work, only setting it the config works
// resolve: {
// external: true,
// },
// },
runnerOptions: {
hmr: {
logger: false,
},
},
'serve',
),
{
// options: {
// consumer: 'server',
// dev: {
// moduleRunnerTransform: true,
// },
// TODO for some reason this doesn't work, only setting it the config works
// resolve: {
// external: true,
// },
// },
runnerOptions: {
hmr: {
logger: false,
},
hot: false,
evaluator: new ESModulesEvaluator({
cjsGlobals: true,
}),
},
)
await environment.init()
hot: false,
},
)
await environment.init()
try {
const { default: userConfig } = (await environment.runner.import(
resolvedPath,
)) as {
default: UserConfigExport
}
debug?.(`config file loaded in ${getTime()}`)

const config = await (typeof userConfig === 'function'
? userConfig(configEnv)
: userConfig)
if (!isObject(config)) {
throw new Error(`config must export or return an object.`)
}
const modules = [
...environment.runner.evaluatedModules.fileToModulesMap.entries(),
]
await environment.runner.close()
const dependencies = modules
.filter(([file, modules]) => {
const isExternal = [...modules].some(
const isExternal = [...modules].every(
(m) => !m.meta || 'externalize' in m.meta,
)
return !isExternal && file !== resolvedPath
})
.map(([file]) => file)
return {
path: normalizePath(resolvedPath),
config,
userConfig,
dependencies,
}
} catch (e) {
await environment?.runner.close()
createLogger(logLevel, { customLogger }).error(
colors.red(`failed to load config from ${resolvedPath}`),
{
error: e,
},
)
throw e
} catch (err) {
await environment.close()
throw err
}
}

Expand Down

0 comments on commit e546e04

Please sign in to comment.