Skip to content

Commit

Permalink
refactor: decouple rolldownDevPlugin
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Nov 11, 2024
1 parent 975fc34 commit 18885d2
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 66 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ import { createIdResolver } from './idResolver'
import { type OxcOptions, convertEsbuildConfigToOxcConfig } from './plugins/oxc'
import {
type RolldownDevOptions,
rolldownDevPluginConfig,
rolldownDevHandleConfig,
} from './server/environments/rolldown'

const debug = createDebugger('vite:config')
Expand Down Expand Up @@ -1016,7 +1016,7 @@ export async function resolveConfig(
const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]
config = await runConfigHook(config, userPlugins, configEnv)
if (config.experimental?.rolldownDev) {
config = mergeConfig(config, rolldownDevPluginConfig(config))
config = mergeConfig(config, rolldownDevHandleConfig(config))
}

// Ensure default client and ssr environments
Expand Down
5 changes: 0 additions & 5 deletions packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,6 @@ export async function resolvePlugins(
})
: importGlobPlugin(config),

// TODO: cyclic import?
!isBuild &&
config.experimental.rolldownDev &&
(await import('../server/environments/rolldown')).rolldownDevPlugin(),

...postPlugins,

...buildPlugins.post,
Expand Down
125 changes: 66 additions & 59 deletions packages/vite/src/node/server/environments/rolldown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { DevEnvironment } from '../environment'
import type {
DevEnvironmentOptions,
HmrContext,
Plugin,
ResolvedConfig,
UserConfig,
ViteDevServer,
Expand All @@ -32,7 +31,7 @@ const logger = createLogger('info', {
allowClearScreen: false,
})

export function rolldownDevPluginConfig(config: UserConfig): UserConfig {
export function rolldownDevHandleConfig(config: UserConfig): UserConfig {
return {
appType: 'custom',
optimizeDeps: {
Expand Down Expand Up @@ -74,65 +73,73 @@ export function rolldownDevPluginConfig(config: UserConfig): UserConfig {
}
}

export function rolldownDevPlugin(): Plugin {
let server: ViteDevServer
let environments: Record<'client' | 'ssr', RolldownEnvironment>
// type casting helper
function asRolldown(server: ViteDevServer): Omit<
ViteDevServer,
'environments'
> & {
environments: {
client: RolldownEnvironment
ssr: RolldownEnvironment
}
} {
return server as any
}

return {
name: 'vite:rolldown-dev',
configureServer(server_) {
server = server_
environments = server.environments as any

// rolldown server as middleware
server.middlewares.use(
sirv(environments.client.outDir, { dev: true, extensions: ['html'] }),
)

// reuse /@vite/client for Websocket API but serve it on our own
// TODO: include it in `rolldown_runtime`?
const rolldownClientCode = getRolldownClientCode()
server.middlewares.use((req, res, next) => {
const url = new URL(req.url ?? '', 'https://rolldown.rs')
if (url.pathname === '/@rolldown/client') {
res.setHeader('content-type', 'text/javascript;charset=utf-8')
res.end(rolldownClientCode)
return
}
next()
})

// full build on non self accepting entry
server.ws.on('rolldown:hmr-deadend', async (data) => {
logger.info(`hmr-deadend '${data.moduleId}'`, { timestamp: true })
await environments.client.build()
server.ws.send({ type: 'full-reload' })
})

// disable automatic html reload
// https://github.com/vitejs/vite/blob/01cf7e14ca63988c05627907e72b57002ffcb8d5/packages/vite/src/node/server/hmr.ts#L590-L595
const oldSend = server.ws.send
server.ws.send = function (...args: any) {
const arg = args[0]
if (
arg &&
typeof arg === 'object' &&
arg.type === 'full-reload' &&
typeof arg.path === 'string' &&
arg.path.endsWith('.html')
) {
return
}
oldSend.apply(this, args)
}
},
async handleHotUpdate(ctx) {
await environments.ssr.handleUpdate(ctx)
await environments.client.handleUpdate(ctx)
},
export function rolldownDevConfigureServer(server: ViteDevServer): void {
const { environments } = asRolldown(server)

// rolldown server as middleware
server.middlewares.use(
sirv(environments.client.outDir, { dev: true, extensions: ['html'] }),
)

// reuse /@vite/client for Websocket API but serve it on our own
// TODO: include it in `rolldown_runtime`?
const rolldownClientCode = getRolldownClientCode()
server.middlewares.use((req, res, next) => {
const url = new URL(req.url ?? '', 'https://rolldown.rs')
if (url.pathname === '/@rolldown/client') {
res.setHeader('content-type', 'text/javascript;charset=utf-8')
res.end(rolldownClientCode)
return
}
next()
})

// full build on non self accepting entry
server.ws.on('rolldown:hmr-deadend', async (data) => {
logger.info(`hmr-deadend '${data.moduleId}'`, { timestamp: true })
await environments.client.build()
server.ws.send({ type: 'full-reload' })
})

// disable automatic html reload
// https://github.com/vitejs/vite/blob/01cf7e14ca63988c05627907e72b57002ffcb8d5/packages/vite/src/node/server/hmr.ts#L590-L595
const oldSend = server.ws.send
server.ws.send = function (...args: any) {
const arg = args[0]
if (
arg &&
typeof arg === 'object' &&
arg.type === 'full-reload' &&
typeof arg.path === 'string' &&
arg.path.endsWith('.html')
) {
return
}
oldSend.apply(this, args)
}
}

export async function rolldownDevHandleHotUpdate(
ctx: HmrContext,
): Promise<void> {
const { environments } = asRolldown(ctx.server)
await environments.ssr.handleUpdate(ctx)
await environments.client.handleUpdate(ctx)
}

function getRolldownClientCode() {
let code = fs.readFileSync(CLIENT_ENTRY, 'utf-8')
const replacements = {
Expand All @@ -149,7 +156,7 @@ function getRolldownClientCode() {
__HMR_CONFIG_NAME__: `""`,
// runtime define is not necessary
[`import '@vite/env';`]: ``,
[`import "@vite/env";`]: ``, // for local dev
[`import "@vite/env";`]: ``, // for local pnpm dev
}
for (const [k, v] of Object.entries(replacements)) {
code = code.replaceAll(k, v)
Expand All @@ -166,7 +173,7 @@ window.__rolldown_hot = hot;
return code
}

export class RolldownEnvironment extends DevEnvironment {
class RolldownEnvironment extends DevEnvironment {
instance!: rolldown.RolldownBuild
result!: rolldown.RolldownOutput
outDir!: string
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type { EnvironmentModuleNode } from './moduleGraph'
import type { ModuleNode } from './mixedModuleGraph'
import type { DevEnvironment } from './environment'
import { prepareError } from './middlewares/error'
import { rolldownDevHandleHotUpdate } from './environments/rolldown'
import type { HttpServer } from '.'
import { restartServerWithUrls } from '.'

Expand Down Expand Up @@ -252,6 +253,10 @@ export async function handleHMRUpdate(
...contextMeta,
modules: [...mixedMods],
}
if (config.experimental.rolldownDev) {
await rolldownDevHandleHotUpdate(mixedHmrContext)
return
}

const clientEnvironment = server.environments.client
const ssrEnvironment = server.environments.ssr
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ import type { TransformOptions, TransformResult } from './transformRequest'
import { transformRequest } from './transformRequest'
import { searchForPackageRoot, searchForWorkspaceRoot } from './searchRoot'
import type { DevEnvironment } from './environment'
import { rolldownDevConfigureServer } from './environments/rolldown'

export interface ServerOptions extends CommonServerOptions {
/**
Expand Down Expand Up @@ -824,6 +825,10 @@ export async function _createServer(
postHooks.push(await hook(reflexServer))
}

if (config.experimental.rolldownDev) {
rolldownDevConfigureServer(reflexServer)
}

// Internal middlewares ------------------------------------------------------

// request timer
Expand Down

0 comments on commit 18885d2

Please sign in to comment.