Skip to content

Commit

Permalink
feat(ssg): make it more polite
Browse files Browse the repository at this point in the history
  • Loading branch information
berlysia committed Feb 16, 2024
1 parent 810b53e commit b26b2fb
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
21 changes: 17 additions & 4 deletions packages/ssg/src/ssg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ export const defaultOptions: Required<SSGOptions> = {
}

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 {
Expand All @@ -22,20 +25,30 @@ export const ssgBuild = (options?: SSGOptions): Plugin => {
return {
build: {
rollupOptions: {
input: [entry],
input: [virtualId],
},
},
}
},
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({
Expand Down
33 changes: 33 additions & 0 deletions packages/ssg/test/ssg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,37 @@ describe('ssgPlugin', () => {
const output = fs.readFileSync(outputFile, 'utf-8')
expect(output).toBe('<html><body><h1>Hello!</h1></body></html>')
})

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

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

0 comments on commit b26b2fb

Please sign in to comment.