|
| 1 | +import { readFileSync } from "node:fs"; |
| 2 | +import { Plugin, defineWorkspace } from "vitest/config"; |
| 3 | +import MagicString from "magic-string"; |
| 4 | + |
| 5 | +export default defineWorkspace([ |
| 6 | + // Project that uses its own "root" and custom transform plugin |
| 7 | + { |
| 8 | + test: { |
| 9 | + name: "custom-with-root", |
| 10 | + root: "fixtures/workspaces/custom-2", |
| 11 | + }, |
| 12 | + plugins: [customFilePlugin("2")], |
| 13 | + }, |
| 14 | + |
| 15 | + // Project that cannot transform "*.custom-x" files |
| 16 | + { |
| 17 | + test: { |
| 18 | + name: "normal", |
| 19 | + include: ["fixtures/test/math.test.ts"], |
| 20 | + }, |
| 21 | + }, |
| 22 | + |
| 23 | + // Project that uses default "root" and has custom transform plugin |
| 24 | + { |
| 25 | + test: { |
| 26 | + name: "custom", |
| 27 | + include: ["fixtures/test/custom-1-syntax.test.ts"], |
| 28 | + }, |
| 29 | + plugins: [customFilePlugin("1")], |
| 30 | + }, |
| 31 | +]); |
| 32 | + |
| 33 | +/** |
| 34 | + * Plugin for transforming `.custom-1` and/or `.custom-2` files to Javascript |
| 35 | + */ |
| 36 | +function customFilePlugin(postfix: "1" | "2"): Plugin { |
| 37 | + function transform(code: MagicString) { |
| 38 | + code.replaceAll( |
| 39 | + "<function covered>", |
| 40 | + ` |
| 41 | +function covered() { |
| 42 | + return "Custom-${postfix} file loaded!" |
| 43 | +} |
| 44 | + `.trim() |
| 45 | + ); |
| 46 | + |
| 47 | + code.replaceAll( |
| 48 | + "<function uncovered>", |
| 49 | + ` |
| 50 | +function uncovered() { |
| 51 | + return "This should be uncovered!" |
| 52 | +} |
| 53 | + `.trim() |
| 54 | + ); |
| 55 | + |
| 56 | + code.replaceAll("<default export covered>", "export default covered()"); |
| 57 | + code.replaceAll("<default export uncovered>", "export default uncovered()"); |
| 58 | + } |
| 59 | + |
| 60 | + return { |
| 61 | + name: `custom-${postfix}-file-plugin`, |
| 62 | + transform(_, id) { |
| 63 | + const filename = id.split("?")[0]; |
| 64 | + |
| 65 | + if (filename.endsWith(`.custom-${postfix}`)) { |
| 66 | + const content = readFileSync(filename, "utf8"); |
| 67 | + |
| 68 | + const s = new MagicString(content); |
| 69 | + transform(s); |
| 70 | + |
| 71 | + return { |
| 72 | + code: s.toString(), |
| 73 | + map: s.generateMap({ hires: "boundary" }), |
| 74 | + }; |
| 75 | + } |
| 76 | + }, |
| 77 | + }; |
| 78 | +} |
0 commit comments