1
1
/** @import { AST } from 'svelte/compiler' */
2
-
3
2
import { existsSync } from 'node:fs' ;
4
3
import path from 'node:path' ;
5
- import { loadSvelteConfig } from '@sveltejs/vite-plugin-svelte' ;
6
4
import MagicString from 'magic-string' ;
7
5
import sharp from 'sharp' ;
8
6
import { parse } from 'svelte-parse-markup' ;
@@ -27,37 +25,30 @@ export function image_plugin(imagetools_plugin) {
27
25
/** @type {import('vite').ResolvedConfig } */
28
26
let vite_config ;
29
27
30
- /** @type {Partial<import('@sveltejs/vite-plugin-svelte').SvelteConfig | undefined> } */
31
- let svelte_config ;
32
-
33
28
const name = 'vite-plugin-enhanced-img-markup' ;
34
29
35
- return {
30
+ /** @type {import('vite').Plugin<void> } */
31
+ const plugin = {
36
32
name,
37
- enforce : 'pre' ,
38
- async configResolved ( config ) {
33
+ configResolved ( config ) {
39
34
vite_config = config ;
40
- for ( const plugin of config . plugins || [ ] ) {
41
- if ( plugin . name === name ) {
42
- break ;
43
- }
44
- if ( plugin . name === 'vite-plugin-svelte' ) {
45
- throw new Error (
46
- '@sveltejs/enhanced-img must come before the Svelte or SvelteKit plugins'
47
- ) ;
48
- }
35
+ const svelteConfigPlugin = config . plugins . find ( ( p ) => p . name === 'vite-plugin-svelte:config' ) ;
36
+ if ( ! svelteConfigPlugin ) {
37
+ throw new Error (
38
+ '@sveltejs/enhanced-img requires @sveltejs/vite-plugin-svelte 6 or higher to be installed'
39
+ ) ;
49
40
}
50
- svelte_config = await loadSvelteConfig ( ) ;
51
- if ( ! svelte_config ) throw new Error ( 'Could not load Svelte config file' ) ;
41
+ // @ts -expect-error plugin.transform is defined below before configResolved is called
42
+ plugin . transform . filter . id = svelteConfigPlugin . api . idFilter ;
52
43
} ,
53
- async transform ( content , filename ) {
54
- const plugin_context = this ;
55
- const extensions = svelte_config ?. extensions || [ '.svelte' ] ;
56
- if ( extensions . some ( ( ext ) => filename . endsWith ( ext ) ) ) {
57
- if ( ! content . includes ( '<enhanced:img' ) ) {
58
- return ;
59
- }
60
-
44
+ transform : {
45
+ order : 'pre' , // puts it before vite-plugin-svelte:compile
46
+ filter : {
47
+ code : / < e n h a n c e d : i m g / // code filter must match in addition to the id filter set in configResolved hook above
48
+ } ,
49
+
50
+ async handler ( content , filename ) {
51
+ const plugin_context = this ;
61
52
const s = new MagicString ( content ) ;
62
53
const ast = parse ( content , { filename, modern : true } ) ;
63
54
@@ -196,11 +187,12 @@ export function image_plugin(imagetools_plugin) {
196
187
197
188
return {
198
189
code : s . toString ( ) ,
199
- map : s . generateMap ( )
190
+ map : s . generateMap ( { hires : 'boundary' } )
200
191
} ;
201
192
}
202
193
}
203
194
} ;
195
+ return plugin ;
204
196
}
205
197
206
198
/**
0 commit comments