diff --git a/packages/nitro/src/rollup/config.ts b/packages/nitro/src/rollup/config.ts index 5594d92b00..9f6fd07e13 100644 --- a/packages/nitro/src/rollup/config.ts +++ b/packages/nitro/src/rollup/config.ts @@ -19,7 +19,7 @@ import { dynamicRequire } from './plugins/dynamic-require' import { externals } from './plugins/externals' import { timing } from './plugins/timing' import { autoMock } from './plugins/automock' -import { staticAssets } from './plugins/static' +import { staticAssets, dirnames } from './plugins/static' import { middleware } from './plugins/middleware' import { esbuild } from './plugins/esbuild' @@ -128,6 +128,7 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => { // Static if (sigmaContext.serveStatic) { + rollupConfig.plugins.push(dirnames()) rollupConfig.plugins.push(staticAssets(sigmaContext)) } diff --git a/packages/nitro/src/rollup/plugins/static.ts b/packages/nitro/src/rollup/plugins/static.ts index 9f27ef3964..095416be40 100644 --- a/packages/nitro/src/rollup/plugins/static.ts +++ b/packages/nitro/src/rollup/plugins/static.ts @@ -4,6 +4,7 @@ import mime from 'mime' import { relative, resolve } from 'upath' import virtual from '@rollup/plugin-virtual' import globby from 'globby' +import type { Plugin } from 'rollup' import type { SigmaContext } from '../../context' export function staticAssets (context: SigmaContext) { @@ -29,14 +30,12 @@ export function staticAssets (context: SigmaContext) { return virtual({ '~static-assets': `export default ${JSON.stringify(assets, null, 2)};`, '~static': ` -import { readFile } from 'fs/promises' -import { resolve, dirname } from 'path' +import { promises } from 'fs' +import { resolve } from 'path' import assets from '~static-assets' -const mainDir = dirname(require.main.filename) - export function readAsset (id) { - return readFile(resolve(mainDir, getAsset(id).path)) + return promises.readFile(resolve(mainDir, getAsset(id).path)) } export function getAsset (id) { @@ -45,3 +44,12 @@ export function getAsset (id) { ` }) } + +export function dirnames (): Plugin { + return { + name: 'dirnames', + renderChunk (code, chunk) { + return code + (chunk.isEntry ? 'global.mainDir="undefined"!=typeof __dirname?__dirname:require.main.filename;' : '') + } + } +}