forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-json.ts
More file actions
42 lines (35 loc) · 1.33 KB
/
generate-json.ts
File metadata and controls
42 lines (35 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { Compilation, Compiler, sources } from '@rspack/core'
type GenerateJsonPluginOptions = {
data: Record<string, unknown>
outputPath: string
}
export class GenerateJsonPlugin {
private options: GenerateJsonPluginOptions
constructor(outputPath: string, data: Record<string, unknown>) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid data option')
}
if (!outputPath?.endsWith('.json')) {
throw new Error('outputPath must be .json file')
}
this.options = { outputPath, data }
}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap('GenerateJsonPlugin', (compilation) => {
compilation.hooks.processAssets.tap({
name: 'GenerateJsonPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, () => {
try {
const json = JSON.stringify(this.options.data)
compilation.emitAsset(this.options.outputPath, {
source: () => json,
size: () => json.length
} as sources.Source)
} catch (e) {
compilation.errors.push(new Error(`[SimpleWriteJson] ${(e as Error)?.message}`))
}
})
})
}
}