From eadeb890132f384bb6868a219d6c94ebf5f98955 Mon Sep 17 00:00:00 2001 From: berlysia Date: Sat, 17 Feb 2024 01:47:50 +0900 Subject: [PATCH] feat(ssg): make it more polite --- packages/ssg/src/ssg.ts | 23 ++++++++++++++++++----- packages/ssg/test/ssg.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/packages/ssg/src/ssg.ts b/packages/ssg/src/ssg.ts index 11a296c..09805ff 100644 --- a/packages/ssg/src/ssg.ts +++ b/packages/ssg/src/ssg.ts @@ -2,7 +2,7 @@ import { relative } from 'node:path' import type { Hono } from 'hono' import { toSSG } from 'hono/ssg' import type { Plugin, ResolvedConfig } from 'vite' -import { createServer } from 'vite' +import { build, createServer } from 'vite' type SSGOptions = { entry?: string @@ -13,6 +13,9 @@ export const defaultOptions: Required = { } export const ssgBuild = (options?: SSGOptions): Plugin => { + const virtualId = 'virtual:ssg-void-entry' + const resolvedVirtualId = '\0' + virtualId + const entry = options?.entry ?? defaultOptions.entry let config: ResolvedConfig return { @@ -22,7 +25,7 @@ export const ssgBuild = (options?: SSGOptions): Plugin => { return { build: { rollupOptions: { - input: [entry], + input: [virtualId], }, }, } @@ -30,12 +33,22 @@ export const ssgBuild = (options?: SSGOptions): Plugin => { configResolved(resolved) { config = resolved }, + resolveId(id) { + if (id === virtualId) { + return resolvedVirtualId + } + }, load(id) { - // discard entry file content - return 'export default {};' + if (id === resolvedVirtualId) { + return '' + } }, async generateBundle(_outputOptions, bundle) { - for (const key in bundle) delete bundle[key] + for (const chunk of Object.values(bundle)) { + if (chunk.type === 'chunk' && chunk.moduleIds.includes(resolvedVirtualId)) { + delete bundle[chunk.fileName] + } + } // Create a server to load the module const server = await createServer({ diff --git a/packages/ssg/test/ssg.test.ts b/packages/ssg/test/ssg.test.ts index dcc8731..02c4692 100644 --- a/packages/ssg/test/ssg.test.ts +++ b/packages/ssg/test/ssg.test.ts @@ -37,4 +37,37 @@ describe('ssgPlugin', () => { const output = fs.readFileSync(outputFile, 'utf-8') expect(output).toBe('

Hello!

') }) + + it('Should keep other inputs politely', async () => { + expect(fs.existsSync(entryFile)).toBe(true) + + await build({ + plugins: [ + ssgPlugin({ + entry: entryFile, + }), + ], + build: { + rollupOptions: { + input: entryFile, + output: { + entryFileNames: 'assets/[name].js', + }, + }, + outDir: path.resolve(testDir, 'dist'), + emptyOutDir: true, + }, + }) + + const entryOutputFile = path.resolve(testDir, 'dist', 'assets', 'app.js') + + expect(fs.existsSync(outputFile)).toBe(true) + expect(fs.existsSync(entryOutputFile)).toBe(true) + + const output = fs.readFileSync(outputFile, 'utf-8') + expect(output).toBe('

Hello!

') + + const entryOutput = fs.readFileSync(entryOutputFile, 'utf-8') + expect(entryOutput.length).toBeGreaterThan(0) + }) })