@@ -31,6 +31,11 @@ export function image(opts) {
31
31
const s = new MagicString ( content ) ;
32
32
const ast = parse ( content , { filename } ) ;
33
33
34
+ // Import path to import name
35
+ // e.g. ./foo.png => ___ASSET___0
36
+ /** @type {Map<string, string> } */
37
+ const imports = new Map ( ) ;
38
+
34
39
/**
35
40
* @param {import('svelte/types/compiler/interfaces').TemplateNode } node
36
41
* @param {{ type: string, start: number, end: number, raw: string } } src_attribute
@@ -46,7 +51,8 @@ export function image(opts) {
46
51
return ;
47
52
}
48
53
49
- let url = src_attribute . raw . trim ( ) ;
54
+ const original_url = src_attribute . raw . trim ( ) ;
55
+ let url = original_url ;
50
56
51
57
const sizes = get_attr_value ( node , 'sizes' ) ;
52
58
const width = get_attr_value ( node , 'width' ) ;
@@ -74,8 +80,17 @@ export function image(opts) {
74
80
if ( OPTIMIZABLE . test ( url ) ) {
75
81
s . update ( node . start , node . end , img_to_picture ( content , node , details ) ) ;
76
82
} else {
77
- // e.g. <img src="./foo.svg" /> => <img src="{___ASSET___0}" />
78
- s . update ( src_attribute . start , src_attribute . end , `{${ details } }` ) ;
83
+ // e.g. <img src="./foo.svg" /> => <img src={___ASSET___0} />
84
+ const { start, end } = src_attribute ;
85
+ // update src with reference to imported asset
86
+ s . update (
87
+ is_quote ( content , start - 1 ) ? start - 1 : start ,
88
+ is_quote ( content , end ) ? end + 1 : end ,
89
+ `{${ details . name } }`
90
+ ) ;
91
+ // update `enhanced:img` to `img`
92
+ s . update ( node . start + 1 , node . start + 1 + 'enhanced:img' . length , 'img' ) ;
93
+ imports . set ( original_url , details . name ) ;
79
94
}
80
95
}
81
96
@@ -97,6 +112,20 @@ export function image(opts) {
97
112
}
98
113
} ) ;
99
114
115
+ // add imports
116
+ if ( imports . size ) {
117
+ let import_text = '' ;
118
+ for ( const [ path , import_name ] of imports . entries ( ) ) {
119
+ import_text += `import ${ import_name } from "${ path } ";` ;
120
+ }
121
+ if ( ast . instance ) {
122
+ // @ts -ignore
123
+ s . appendLeft ( ast . instance . content . start , import_text ) ;
124
+ } else {
125
+ s . append ( `<script>${ import_text } </script>` ) ;
126
+ }
127
+ }
128
+
100
129
return {
101
130
code : s . toString ( ) ,
102
131
map : s . generateMap ( )
@@ -105,6 +134,15 @@ export function image(opts) {
105
134
} ;
106
135
}
107
136
137
+ /**
138
+ * @param {string } content
139
+ * @param {number } index
140
+ * @returns {boolean }
141
+ */
142
+ function is_quote ( content , index ) {
143
+ return content . charAt ( index ) === '"' || content . charAt ( index ) === "'" ;
144
+ }
145
+
108
146
/**
109
147
* @param {{
110
148
* plugin_context: import('rollup').PluginContext
0 commit comments