|
| 1 | +import { defineConfig } from 'waku/config'; |
| 2 | +import type { Plugin } from 'vite'; |
| 3 | +import path from 'node:path'; |
| 4 | +import fs from 'node:fs'; |
| 5 | + |
| 6 | +export default defineConfig({ |
| 7 | + unstable_viteConfigs: { |
| 8 | + 'build-server': () => ({ |
| 9 | + plugins: [importMetaUrlServerPlugin()], |
| 10 | + }), |
| 11 | + }, |
| 12 | +}); |
| 13 | + |
| 14 | +// emit asset and rewrite `new URL("./xxx", import.meta.url)` syntax for build. |
| 15 | +function importMetaUrlServerPlugin(): Plugin { |
| 16 | + // https://github.com/vitejs/vite/blob/0f56e1724162df76fffd5508148db118767ebe32/packages/vite/src/node/plugins/assetImportMetaUrl.ts#L51-L52 |
| 17 | + const assetImportMetaUrlRE = |
| 18 | + /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg; |
| 19 | + |
| 20 | + return { |
| 21 | + name: 'test-server-asset', |
| 22 | + transform(code, id) { |
| 23 | + return code.replace(assetImportMetaUrlRE, (s, match) => { |
| 24 | + const absPath = path.resolve(path.dirname(id), match.slice(1, -1)); |
| 25 | + if (fs.existsSync(absPath)) { |
| 26 | + const referenceId = this.emitFile({ |
| 27 | + type: 'asset', |
| 28 | + name: path.basename(absPath), |
| 29 | + source: new Uint8Array(fs.readFileSync(absPath)), |
| 30 | + }); |
| 31 | + return `new URL(import.meta.ROLLUP_FILE_URL_${referenceId})`; |
| 32 | + } |
| 33 | + return s; |
| 34 | + }); |
| 35 | + }, |
| 36 | + }; |
| 37 | +} |
0 commit comments