|
7 | 7 | >
|
8 | 8 | > **Proceed with caution!**
|
9 | 9 |
|
| 10 | +## transform svelte files with vite plugins |
| 11 | + |
| 12 | +vite-plugin-svelte uses 2 Vite plugins `vite-plugin-svelte:preprocess` and `vite-plugin-svelte:compile` to preprocess and compile input. |
| 13 | +The preprocess plugin uses `enforce: pre` but the compile plugin does not, giving you fine-grained control to add your own transforms |
| 14 | + |
| 15 | +```js |
| 16 | +function mySvelteTransform() { |
| 17 | + const plugin = { |
| 18 | + name: 'vite-plugin-my-svelte-transformer', |
| 19 | + configResolved(c) { |
| 20 | + // optional, use the exact same id filter as vite-plugin-svelte itself |
| 21 | + const svelteIdFilter = c.plugins.find((p) => p.name === 'vite-plugin-svelte:config').api |
| 22 | + .idFilter; |
| 23 | + plugin.transform.filter.id = svelteIdFilter; |
| 24 | + }, |
| 25 | + transform: { |
| 26 | + // if you don't use vite-plugin-svelte's filter make sure to include your own here |
| 27 | + filter: { id: /your id filter here/ }, |
| 28 | + async handler(code, id) { |
| 29 | + const s = new MagicString(code); |
| 30 | + // do your transforms with s |
| 31 | + return { |
| 32 | + code: s.toString(), |
| 33 | + map: s.generateMap({ hires: 'boundary', includeContent: false }) |
| 34 | + }; |
| 35 | + } |
| 36 | + } |
| 37 | + }; |
| 38 | + // To add your transform in the correct place use `enforce` and `transform.order` |
| 39 | + |
| 40 | + // before preprocess |
| 41 | + plugin.enforce = 'pre'; |
| 42 | + plugin.transform.order = 'pre'; |
| 43 | + |
| 44 | + // after preprocess but before compile |
| 45 | + plugin.transform.order = 'pre'; // leave plugin.enforce undefined |
| 46 | + |
| 47 | + // after compile |
| 48 | + plugin.transform.order = 'post'; // leave plugin.enforce undefined |
| 49 | + |
| 50 | + return plugin; |
| 51 | +} |
| 52 | +``` |
| 53 | + |
10 | 54 | ## custom queries
|
11 | 55 |
|
12 | 56 | Vite supports using query parameters to request different outcomes for the same file.
|
|
0 commit comments