Skip to content
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(ssg): make it simple #80

Merged
merged 6 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chatty-moose-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hono/vite-ssg": minor
---

Simplify the build flow. Just run `toSSG`. Respect Vite's config.
12 changes: 0 additions & 12 deletions packages/ssg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,8 @@ wrangler pages deploy ./dist
The options are below.

```ts
type BuildConfig = {
outputDir?: string
publicDir?: string
}

type SSGOptions = {
entry?: string
rootDir?: string
build?: BuildConfig
}
```

Expand All @@ -75,11 +68,6 @@ Default values:
```ts
const defaultOptions = {
entry: './src/index.tsx',
tempDir: '.hono',
build: {
outputDir: '../dist',
publicDir: '../public',
},
}
```

Expand Down
89 changes: 53 additions & 36 deletions packages/ssg/src/ssg.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,55 @@
import fs from 'node:fs/promises'
import { relative } from 'node:path'
import type { Hono } from 'hono'
import { toSSG } from 'hono/ssg'
import type { Plugin } from 'vite'
import type { Plugin, ResolvedConfig } from 'vite'
import { createServer } from 'vite'

type BuildConfig = {
outputDir?: string
publicDir?: string
}

type SSGOptions = {
entry?: string
tempDir?: string
build?: BuildConfig
}

export const defaultOptions: Required<SSGOptions> = {
entry: './src/index.tsx',
tempDir: '.hono',
build: {
outputDir: '../dist',
publicDir: '../public',
},
}

export const ssgBuild = (options?: SSGOptions): Plugin => {
const virtualId = 'virtual:ssg-void-entry'
const resolvedVirtualId = '\0' + virtualId

const entry = options?.entry ?? defaultOptions.entry
const tempDir = options?.tempDir ?? defaultOptions.tempDir
let config: ResolvedConfig
return {
name: '@hono/vite-ssg',
apply: 'build',
config: async () => {
async config() {
return {
build: {
rollupOptions: {
input: [virtualId],
},
},
}
},
configResolved(resolved) {
config = resolved
},
resolveId(id) {
if (id === virtualId) {
return resolvedVirtualId
}
},
load(id) {
if (id === resolvedVirtualId) {
return 'console.log("suppress empty chunk message")'
}
},
async generateBundle(_outputOptions, bundle) {
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({
plugins: [],
Expand All @@ -45,31 +64,29 @@ export const ssgBuild = (options?: SSGOptions): Plugin => {
throw new Error(`Failed to find a named export "default" from ${entry}`)
}

console.log(`Build files into temp directory: ${tempDir}`)
const outDir = config.build.outDir
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using outDir from Vite's config is good!


const result = await toSSG(app, fs, { dir: tempDir })
const result = await toSSG(
app,
{
writeFile: async (path, data) => {
// delegate to Vite to emit the file
this.emitFile({
type: 'asset',
fileName: relative(outDir, path),
source: data,
})
},
async mkdir() {
return
},
},
{ dir: outDir }
)

if (!result.success) {
throw result.error
}

if (result.files) {
for (const file of result.files) {
console.log(`Generated: ${file}`)
}
}

return {
root: tempDir,
publicDir: options?.build?.publicDir ?? defaultOptions.build.publicDir,
build: {
outDir: options?.build?.outputDir ?? defaultOptions.build.outputDir,
rollupOptions: {
input: result.files ? [...result.files] : [],
},
emptyOutDir: true,
},
}
},
}
}
41 changes: 39 additions & 2 deletions packages/ssg/test/ssg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import ssgPlugin from '../src/index'
describe('ssgPlugin', () => {
const testDir = './test-project'
const entryFile = './test/app.ts'
const outputFile = path.resolve(testDir, 'dist', 'index.html')
const outDir = path.resolve(testDir, 'dist')
const outputFile = path.resolve(outDir, 'index.html')

beforeAll(() => {
fs.mkdirSync(testDir, { recursive: true })
Expand All @@ -24,10 +25,10 @@ describe('ssgPlugin', () => {
plugins: [
ssgPlugin({
entry: entryFile,
tempDir: path.resolve(testDir, '.hono'),
}),
],
build: {
outDir,
emptyOutDir: true,
},
})
Expand All @@ -36,5 +37,41 @@ describe('ssgPlugin', () => {

const output = fs.readFileSync(outputFile, 'utf-8')
expect(output).toBe('<html><body><h1>Hello!</h1></body></html>')

// Should not output files corresponding to a virtual entry
expect(fs.existsSync(path.resolve(outDir, 'assets'))).toBe(false)
})

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,
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('<html><body><h1>Hello!</h1></body></html>')

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