-
-
Notifications
You must be signed in to change notification settings - Fork 30
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
feat: port upstream vite-node
dev server implementation
#779
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
73a1531
feat: upstream vite-node-server
wattanx d928d2a
Merge branch 'main' into upstream-vite-node
wattanx 836ad28
fix: add viteOptions into nuxt.options
wattanx cdd0f86
fix: upstream vite warmup
wattanx abf89e3
Merge branch 'main' into upstream-vite-node
wattanx f01f873
fix: fix entry file
wattanx 31f3e7e
Revert "fix: fix entry file"
wattanx 488ee23
Merge remote-tracking branch 'origin/main' into upstream-vite-node
danielroe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { fileURLToPath } from 'node:url' | ||
import { dirname, resolve } from 'pathe' | ||
|
||
let _distDir = dirname(fileURLToPath(import.meta.url)) | ||
if (_distDir.match(/(chunks|shared)$/)) { | ||
_distDir = dirname(_distDir) | ||
} | ||
export const distDir = _distDir | ||
export const pkgDir = resolve(distDir, '..') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -147,3 +147,55 @@ export async function writeClientManifest (clientManifest: any, buildDir: string | |
await fse.writeFile(resolve(buildDir, 'dist/server/client.manifest.json'), clientManifestJSON, 'utf-8') | ||
await fse.writeFile(resolve(buildDir, 'dist/server/client.manifest.mjs'), `export default ${clientManifestJSON}`, 'utf-8') | ||
} | ||
|
||
export async function writeManifest (ctx: ViteBuildContext, css: string[] = []) { | ||
// Write client manifest for use in vue-bundle-renderer | ||
const clientDist = resolve(ctx.nuxt.options.buildDir, 'dist/client') | ||
const serverDist = resolve(ctx.nuxt.options.buildDir, 'dist/server') | ||
|
||
const devClientManifest: Manifest = { | ||
'@vite/client': { | ||
isEntry: true, | ||
file: '@vite/client', | ||
css, | ||
module: true, | ||
resourceType: 'script' | ||
}, | ||
'entry.mjs': { | ||
isEntry: true, | ||
file: 'entry.mjs', | ||
Comment on lines
+164
to
+166
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changes made to original code. original code is [ctx.entry]: {
isEntry: true, // no change
file: ctx.entry
} |
||
module: true, | ||
resourceType: 'script' | ||
} | ||
} | ||
|
||
const clientManifest = ctx.nuxt.options.dev | ||
? devClientManifest | ||
: await fse.readJSON(resolve(clientDist, 'manifest.json')) | ||
|
||
const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(ctx.nuxt.options.app.buildAssetsDir)) | ||
const BASE_RE = new RegExp(`^${escapeRE(buildAssetsDir)}`) | ||
|
||
for (const key in clientManifest) { | ||
if (clientManifest[key].file) { | ||
clientManifest[key].file = clientManifest[key].file.replace(BASE_RE, '') | ||
} | ||
for (const item of ['css', 'assets']) { | ||
if (clientManifest[key][item]) { | ||
clientManifest[key][item] = clientManifest[key][item].map((i: string) => i.replace(BASE_RE, '')) | ||
} | ||
} | ||
} | ||
|
||
await fse.mkdirp(serverDist) | ||
|
||
const manifest = normalizeViteManifest(clientManifest) | ||
await ctx.nuxt.callHook('build:manifest', manifest) | ||
|
||
await fse.writeFile(resolve(serverDist, 'client.manifest.json'), JSON.stringify(manifest, null, 2), 'utf8') | ||
await fse.writeFile(resolve(serverDist, 'client.manifest.mjs'), 'export default ' + JSON.stringify(manifest, null, 2), 'utf8') | ||
|
||
if (!ctx.nuxt.options.dev) { | ||
await fse.rm(resolve(clientDist, 'manifest.json'), { force: true }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
// @ts-check | ||
import { viteNodeFetch } from './vite-node-shared.mjs' | ||
|
||
export default () => viteNodeFetch('/manifest') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
// @ts-check | ||
import { Agent as HTTPSAgent } from 'node:https' | ||
import { $fetch } from 'ofetch' | ||
|
||
export const viteNodeOptions = JSON.parse(process.env.NUXT_VITE_NODE_OPTIONS || '{}') | ||
|
||
export const viteNodeFetch = $fetch.create({ | ||
baseURL: viteNodeOptions.baseURL, | ||
// @ts-expect-error https://github.com/node-fetch/node-fetch#custom-agent | ||
agent: viteNodeOptions.baseURL.startsWith('https://') | ||
? new HTTPSAgent({ rejectUnauthorized: false }) | ||
: null | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
// @ts-check | ||
|
||
import { performance } from 'node:perf_hooks' | ||
import { createError } from 'h3' | ||
import { ViteNodeRunner } from 'vite-node/client' | ||
import { consola } from 'consola' | ||
import { viteNodeFetch, viteNodeOptions } from './vite-node-shared.mjs' | ||
|
||
const runner = createRunner() | ||
/** @type {(ssrContext: import('../../../types').NuxtSSRContext) => Promise<any>} */ | ||
let render | ||
|
||
/** @param ssrContext {import('../../../').NuxtSSRContext} */ | ||
export default async (ssrContext) => { | ||
// Workaround for stub mode | ||
// https://github.com/nuxt/framework/pull/3983 | ||
process.server = true | ||
|
||
// Invalidate cache for files changed since last rendering | ||
const invalidates = await viteNodeFetch('/invalidates') | ||
const updates = runner.moduleCache.invalidateDepTree(invalidates) | ||
|
||
// Execute SSR bundle on demand | ||
const start = performance.now() | ||
render = (updates.has(viteNodeOptions.entryPath) || !render) ? (await runner.executeFile(viteNodeOptions.entryPath)).default : render | ||
if (updates.size) { | ||
const time = Math.round((performance.now() - start) * 1000) / 1000 | ||
consola.success(`Vite server hmr ${updates.size} files`, time ? `in ${time}ms` : '') | ||
} | ||
|
||
const result = await render(ssrContext) | ||
return result | ||
} | ||
|
||
function createRunner () { | ||
const _importers = new Map() | ||
return new ViteNodeRunner({ | ||
root: viteNodeOptions.root, // Equals to Nuxt `srcDir` | ||
base: viteNodeOptions.base, | ||
resolveId (id, importer) { _importers.set(id, importer) }, | ||
async fetchModule (id) { | ||
const importer = _importers.get(id) | ||
_importers.delete(id) | ||
id = id.replace(/\/\//g, '/') // TODO: fix in vite-node | ||
return await viteNodeFetch('/module/' + encodeURI(id)).catch((err) => { | ||
const errorData = err?.data?.data | ||
if (!errorData) { | ||
throw err | ||
} | ||
let _err | ||
try { | ||
const { message, stack } = formatViteError(errorData, id, importer) | ||
_err = createError({ | ||
statusMessage: 'Vite Error', | ||
message, | ||
stack | ||
}) | ||
} catch (formatError) { | ||
consola.warn('Internal nuxt error while formatting vite-node error. Please report this!', formatError) | ||
const message = `[vite-node] [TransformError] ${errorData?.message || '-'}` | ||
consola.error(message, errorData) | ||
throw createError({ | ||
statusMessage: 'Vite Error', | ||
message, | ||
stack: `${message}\nat ${id}\n` + (errorData?.stack || '') | ||
}) | ||
} | ||
throw _err | ||
}) | ||
} | ||
}) | ||
} | ||
|
||
/** | ||
* @param errorData {any} | ||
* @param id {string} | ||
* @param importer {string} | ||
*/ | ||
function formatViteError (errorData, id, importer) { | ||
const errorCode = errorData.name || errorData.reasonCode || errorData.code | ||
const frame = errorData.frame || errorData.source || errorData.pluginCode | ||
|
||
/** @param locObj {{ file?: string, id?: string, url?: string }} */ | ||
const getLocId = (locObj = {}) => locObj.file || locObj.id || locObj.url || id || '' | ||
/** @param locObj {{ line?: string, column?: string }} */ | ||
const getLocPos = (locObj = {}) => locObj.line ? `${locObj.line}:${locObj.column || 0}` : '' | ||
const locId = getLocId(errorData.loc) || getLocId(errorData.location) || getLocId(errorData.input) || getLocId(errorData) | ||
const locPos = getLocPos(errorData.loc) || getLocPos(errorData.location) || getLocPos(errorData.input) || getLocPos(errorData) | ||
const loc = locId.replace(process.cwd(), '.') + (locPos ? `:${locPos}` : '') | ||
|
||
const message = [ | ||
'[vite-node]', | ||
errorData.plugin && `[plugin:${errorData.plugin}]`, | ||
errorCode && `[${errorCode}]`, | ||
loc, | ||
errorData.reason && `: ${errorData.reason}`, | ||
frame && `<br><pre>${frame.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}</pre><br>` | ||
].filter(Boolean).join(' ') | ||
|
||
const stack = [ | ||
message, | ||
`at ${loc} ${importer ? `(imported from ${importer})` : ''}`, | ||
errorData.stack | ||
].filter(Boolean).join('\n') | ||
|
||
return { | ||
message, | ||
stack | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import type { ExternalsOptions } from 'externality' | ||
import { ExternalsDefaults, isExternal } from 'externality' | ||
import type { ViteDevServer } from 'vite' | ||
|
||
export function createIsExternal (viteServer: ViteDevServer, rootDir: string) { | ||
const externalOpts: ExternalsOptions = { | ||
inline: [ | ||
/virtual:/, | ||
/\.ts$/, | ||
...ExternalsDefaults.inline || [], | ||
...Array.isArray(viteServer.config.ssr.noExternal) ? viteServer.config.ssr.noExternal : [] | ||
], | ||
external: [ | ||
...viteServer.config.ssr.external || [], | ||
/node_modules/ | ||
], | ||
resolve: { | ||
type: 'module', | ||
extensions: ['.ts', '.js', '.json', '.vue', '.mjs', '.jsx', '.tsx', '.wasm'] | ||
} | ||
} | ||
|
||
return (id: string) => isExternal(id, rootDir, externalOpts) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changes made to original code.
original code is