2
2
3
3
import { existsSync } from 'node:fs' ;
4
4
import path from 'node:path' ;
5
- import process from 'node:process' ;
6
- import url from 'node:url' ;
5
+ import { loadSvelteConfig } from '@sveltejs/vite-plugin-svelte' ;
7
6
import MagicString from 'magic-string' ;
8
7
import sharp from 'sharp' ;
9
8
import { parse } from 'svelte-parse-markup' ;
@@ -15,9 +14,9 @@ const OPTIMIZABLE = /^[^?]+\.(avif|heif|gif|jpeg|jpg|png|tiff|webp)(\?.*)?$/;
15
14
/**
16
15
* Creates the Svelte image plugin.
17
16
* @param {import('vite').Plugin<void> } imagetools_plugin
18
- * @returns {Promise< import('vite').Plugin<void> > }
17
+ * @returns {import('vite').Plugin<void> }
19
18
*/
20
- export async function image_plugin ( imagetools_plugin ) {
19
+ export function image_plugin ( imagetools_plugin ) {
21
20
// TODO: clear this map in dev mode to avoid memory leak
22
21
/**
23
22
* URL to image details
@@ -28,17 +27,20 @@ export async function image_plugin(imagetools_plugin) {
28
27
/** @type {import('vite').ResolvedConfig } */
29
28
let vite_config ;
30
29
31
- const svelte_config = await load_config ( ) ;
32
- const extensions = svelte_config . extensions || [ '.svelte' ] ;
30
+ /** @type { Partial<import('@sveltejs/vite-plugin-svelte').SvelteConfig | undefined> } */
31
+ let svelte_config ;
33
32
34
33
return {
35
34
name : 'vite-plugin-enhanced-img-markup' ,
36
35
enforce : 'pre' ,
37
- configResolved ( config ) {
36
+ async configResolved ( config ) {
38
37
vite_config = config ;
38
+ svelte_config = await loadSvelteConfig ( ) ;
39
+ if ( ! svelte_config ) throw new Error ( 'Could not load Svelte config file' ) ;
39
40
} ,
40
41
async transform ( content , filename ) {
41
42
const plugin_context = this ;
43
+ const extensions = svelte_config ?. extensions || [ '.svelte' ] ;
42
44
if ( extensions . some ( ( ext ) => filename . endsWith ( ext ) ) ) {
43
45
if ( ! content . includes ( '<enhanced:img' ) ) {
44
46
return ;
@@ -378,28 +380,3 @@ function dynamic_img_to_picture(content, node, src_var_name) {
378
380
</picture>
379
381
{/if}` ;
380
382
}
381
-
382
- /**
383
- * Loads and validates svelte.config.js
384
- * @param {{ cwd?: string } } options
385
- * @returns {Promise<{extensions?: string[]}> }
386
- */
387
- export async function load_config ( { cwd = process . cwd ( ) } = { } ) {
388
- const config_file = path . join ( cwd , 'svelte.config.js' ) ;
389
-
390
- if ( ! existsSync ( config_file ) ) {
391
- return { } ;
392
- }
393
-
394
- const config = await import ( `${ url . pathToFileURL ( config_file ) . href } ?ts=${ Date . now ( ) } ` ) ;
395
-
396
- try {
397
- return config . default ;
398
- } catch ( e ) {
399
- const error = /** @type {Error } */ ( e ) ;
400
-
401
- // redact the stack trace — it's not helpful to users
402
- error . stack = `Could not load svelte.config.js: ${ error . message } \n` ;
403
- throw error ;
404
- }
405
- }
0 commit comments