diff --git a/packages/bridge/src/nitro.ts b/packages/bridge/src/nitro.ts index a7d0b0a1ef..92fdefa65c 100644 --- a/packages/bridge/src/nitro.ts +++ b/packages/bridge/src/nitro.ts @@ -1,11 +1,13 @@ import { promises as fsp } from 'fs' import fetch from 'node-fetch' +import fse from 'fs-extra' import { addPluginTemplate, useNuxt } from '@nuxt/kit' -import { joinURL, stringifyQuery } from 'ufo' +import { joinURL, stringifyQuery, withoutTrailingSlash } from 'ufo' import { resolve, join } from 'pathe' import { build, generate, prepare, getNitroContext, NitroContext, createDevServer, wpfs, resolveMiddleware, scanMiddleware, writeTypes } from '@nuxt/nitro' import { AsyncLoadingPlugin } from './async-loading' import { distDir } from './dirs' +import { isDirectory, readDirRecursively } from './vite/utils/fs' export function setupNitroBridge () { const nuxt = useNuxt() @@ -69,6 +71,34 @@ export function setupNitroBridge () { }) } + nuxt.hook('nitro:generate', async () => { + const clientDist = resolve(nuxt.options.buildDir, 'dist/client') + + // Remove public files that have been duplicated into buildAssetsDir + // TODO: Add option to configure this behaviour in vite + const publicDir = join(nuxt.options.srcDir, nuxt.options.dir.static) + let publicFiles: string[] = [] + if (await isDirectory(publicDir)) { + publicFiles = readDirRecursively(publicDir).map(r => r.replace(publicDir, '')) + for (const file of publicFiles) { + try { + fse.rmSync(join(clientDist, file)) + } catch {} + } + } + + // Copy doubly-nested /_nuxt/_nuxt files into buildAssetsDir + // TODO: Workaround vite issue + if (await isDirectory(clientDist)) { + const nestedAssetsPath = withoutTrailingSlash(join(clientDist, nuxt.options.app.buildAssetsDir)) + + if (await isDirectory(nestedAssetsPath)) { + await fse.copy(nestedAssetsPath, clientDist, { recursive: true }) + await fse.remove(nestedAssetsPath) + } + } + }) + // Expose process.env.NITRO_PRESET nuxt.options.env.NITRO_PRESET = nitroContext.preset diff --git a/packages/bridge/src/vite/utils/fs.ts b/packages/bridge/src/vite/utils/fs.ts new file mode 100644 index 0000000000..e5f5c9b232 --- /dev/null +++ b/packages/bridge/src/vite/utils/fs.ts @@ -0,0 +1,18 @@ +import { promises as fsp, readdirSync, statSync } from 'fs' +import { join } from 'pathe' + +export function readDirRecursively (dir: string) { + return readdirSync(dir).reduce((files, file) => { + const name = join(dir, file) + const isDirectory = statSync(name).isDirectory() + return isDirectory ? [...files, ...readDirRecursively(name)] : [...files, name] + }, []) +} + +export async function isDirectory (path: string) { + try { + return (await fsp.stat(path)).isDirectory() + } catch (_err) { + return false + } +}