| 4 | const nsConfigVirtualId = '\0nsvite:nsconfig-json'; |
| 5 | |
| 6 | export default function nsConfigAsJsonPlugin(): Plugin { |
| 7 | // will hold your parsed config object |
| 8 | let configObject: Record<string, any>; |
| 9 | |
| 10 | return { |
| 11 | name: 'nsvite-nsconfig-as-json', |
| 12 | |
| 13 | // 1. Intercept imports of "~/package.json" |
| 14 | resolveId(source) { |
| 15 | if (source === '~/package.json') { |
| 16 | return nsConfigVirtualId; |
| 17 | } |
| 18 | return null; |
| 19 | }, |
| 20 | |
| 21 | // 2. When Vite asks us to load that virtual ID... |
| 22 | load(id) { |
| 23 | if (id === nsConfigVirtualId) { |
| 24 | configObject = nsConfigToJson(); |
| 25 | |
| 26 | // c) Return an ESM wrapper so Vite can import it at build‑time |
| 27 | return `export default ${JSON.stringify(configObject)};`; |
| 28 | } |
| 29 | return null; |
| 30 | }, |
| 31 | |
| 32 | // 3. After Rollup has generated all chunks, emit a package.json asset |
| 33 | // into the output directory (dist/ by default) |
| 34 | generateBundle(_options, _bundle) { |
| 35 | const json = JSON.stringify(configObject, null, 2); |
| 36 | this.emitFile({ |
| 37 | type: 'asset', |
| 38 | fileName: 'package.json', |
| 39 | source: json, |
| 40 | }); |
| 41 | }, |
| 42 | }; |
| 43 | } |