Skip to content

Commit a41404b

Browse files
monam2cwkang
andauthored
feat(html): add html.additionalAssetSources option (#21412)
Co-authored-by: cwkang <[email protected]>
1 parent 7ca7c1b commit a41404b

7 files changed

Lines changed: 213 additions & 9 deletions

File tree

‎docs/config/shared-options.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,48 @@ Enables the tsconfig paths resolution feature. `paths` option in `tsconfig.json`
214214

215215
A nonce value placeholder that will be used when generating script / style tags. Setting this value will also generate a meta tag with nonce value.
216216

217+
## html.additionalAssetSources
218+
219+
- **Type:** `Record<string, HtmlAssetSource>`
220+
221+
```ts
222+
interface HtmlAssetSource {
223+
srcAttributes?: string[]
224+
srcsetAttributes?: string[]
225+
filter?: (data: {
226+
key: string
227+
value: string
228+
attributes: Record<string, string>
229+
}) => boolean
230+
}
231+
```
232+
233+
Define additional HTML elements and attributes to be treated as asset sources. This extends the built-in list that includes standard elements like `<img src>`, `<video src>`, `<link href>`, etc.
234+
235+
This is useful when using custom web components or non-standard attributes (like `data-*`) that reference assets.
236+
237+
**Example:**
238+
239+
```js
240+
export default defineConfig({
241+
html: {
242+
additionalAssetSources: {
243+
// Custom web component
244+
'html-import': { srcAttributes: ['src'] },
245+
// Add data-* attributes to existing element
246+
img: { srcAttributes: ['data-src-dark', 'data-src-light'] },
247+
// With srcset format
248+
'my-picture': { srcsetAttributes: ['data-srcset'] },
249+
// With filter function
250+
'my-component': {
251+
srcAttributes: ['asset'],
252+
filter: ({ attributes }) => attributes.type === 'image',
253+
},
254+
},
255+
},
256+
})
257+
```
258+
217259
## css.modules
218260

219261
- **Type:**

‎packages/vite/src/node/__tests__/assetSource.spec.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,103 @@ describe('getNodeAssetAttributes', () => {
9494
const attrs = getNodeAssetAttributes(node)
9595
expect(attrs).toHaveLength(0)
9696
})
97+
98+
describe('with additionalAssetSources', () => {
99+
test('handles custom element with additional asset source', () => {
100+
const node = getNode('<html-import src="./file.html"></html-import>')
101+
expect(getNodeAssetAttributes(node)).toHaveLength(0)
102+
const attrs = getNodeAssetAttributes(node, {
103+
'html-import': { srcAttributes: ['src'] },
104+
})
105+
expect(attrs).toHaveLength(1)
106+
expect(attrs[0]).toHaveProperty('type', 'src')
107+
expect(attrs[0]).toHaveProperty('key', 'src')
108+
expect(attrs[0]).toHaveProperty('value', './file.html')
109+
})
110+
111+
test('handles data-* attributes with additional asset source', () => {
112+
const node = getNode('<img src="default.png" data-src-dark="dark.png">')
113+
const defaultAttrs = getNodeAssetAttributes(node)
114+
expect(defaultAttrs).toHaveLength(1)
115+
expect(defaultAttrs[0]).toHaveProperty('key', 'src')
116+
const attrs = getNodeAssetAttributes(node, {
117+
img: { srcAttributes: ['data-src-dark'] },
118+
})
119+
expect(attrs).toHaveLength(2)
120+
expect(attrs[0]).toHaveProperty('key', 'src')
121+
expect(attrs[0]).toHaveProperty('value', 'default.png')
122+
expect(attrs[1]).toHaveProperty('key', 'data-src-dark')
123+
expect(attrs[1]).toHaveProperty('value', 'dark.png')
124+
})
125+
126+
test('additional source with srcset attribute', () => {
127+
const node = getNode(
128+
'<my-picture data-srcset="small.jpg 1x, large.jpg 2x">',
129+
)
130+
const attrs = getNodeAssetAttributes(node, {
131+
'my-picture': { srcsetAttributes: ['data-srcset'] },
132+
})
133+
expect(attrs).toHaveLength(1)
134+
expect(attrs[0]).toHaveProperty('type', 'srcset')
135+
expect(attrs[0]).toHaveProperty('key', 'data-srcset')
136+
})
137+
138+
test('additional source with filter function', () => {
139+
const node = getNode('<my-component type="image" asset="photo.jpg">')
140+
const attrs = getNodeAssetAttributes(node, {
141+
'my-component': {
142+
srcAttributes: ['asset'],
143+
filter: ({ attributes }) => attributes.type === 'image',
144+
},
145+
})
146+
expect(attrs).toHaveLength(1)
147+
expect(attrs[0]).toHaveProperty('value', 'photo.jpg')
148+
const node2 = getNode('<my-component type="text" asset="data.txt">')
149+
const attrs2 = getNodeAssetAttributes(node2, {
150+
'my-component': {
151+
srcAttributes: ['asset'],
152+
filter: ({ attributes }) => attributes.type === 'image',
153+
},
154+
})
155+
expect(attrs2).toHaveLength(0)
156+
})
157+
158+
test('default filter and additional filter are applied independently', () => {
159+
const node = getNode(
160+
'<meta name="twitter:image" content="image.jpg" data-fallback="fallback.jpg">',
161+
)
162+
const attrs = getNodeAssetAttributes(node, {
163+
meta: {
164+
srcAttributes: ['data-fallback'],
165+
filter: ({ key }) => key === 'data-fallback',
166+
},
167+
})
168+
expect(attrs).toHaveLength(2)
169+
expect(attrs[0]).toHaveProperty('key', 'content')
170+
expect(attrs[0]).toHaveProperty('value', 'image.jpg')
171+
expect(attrs[1]).toHaveProperty('key', 'data-fallback')
172+
expect(attrs[1]).toHaveProperty('value', 'fallback.jpg')
173+
})
174+
175+
test('additional filter does not affect default filter behavior', () => {
176+
const node = getNode('<meta name="unknown" content="image.jpg">')
177+
const defaultAttrs = getNodeAssetAttributes(node)
178+
expect(defaultAttrs).toHaveLength(0)
179+
180+
const attrs = getNodeAssetAttributes(node, {
181+
meta: {
182+
srcAttributes: ['data-custom'],
183+
filter: () => true,
184+
},
185+
})
186+
expect(attrs).toHaveLength(0)
187+
})
188+
189+
test('works without additionalAssetSources (backward compatibility)', () => {
190+
const node = getNode('<img src="foo.jpg">')
191+
const attrs = getNodeAssetAttributes(node)
192+
expect(attrs).toHaveLength(1)
193+
expect(attrs[0]).toHaveProperty('key', 'src')
194+
})
195+
})
97196
})

‎packages/vite/src/node/assetSource.ts‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,19 @@
11
import type { DefaultTreeAdapterMap, Token } from 'parse5'
22

3-
interface HtmlAssetSource {
3+
/**
4+
* Defines which attributes of an HTML element should be treated as asset sources.
5+
* Used in `html.additionalAssetSources` configuration.
6+
*/
7+
export interface HtmlAssetSource {
8+
/**
9+
* Attributes that contain a single asset URL.
10+
* @example ['src', 'data-src-dark']
11+
*/
412
srcAttributes?: string[]
13+
/**
14+
* Attributes that contain srcset-format URLs.
15+
* @example ['srcset', 'imagesrcset']
16+
*/
517
srcsetAttributes?: string[]
618
/**
719
* Called before handling an attribute to determine if it should be processed.
@@ -110,9 +122,12 @@ interface HtmlAssetAttribute {
110122
*/
111123
export function getNodeAssetAttributes(
112124
node: DefaultTreeAdapterMap['element'],
125+
additionalAssetSources?: Record<string, HtmlAssetSource>,
113126
): HtmlAssetAttribute[] {
114-
const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName]
115-
if (!matched) return []
127+
const defaults = DEFAULT_HTML_ASSET_SOURCES[node.nodeName]
128+
const additional = additionalAssetSources?.[node.nodeName]
129+
130+
if (!defaults && !additional) return []
116131

117132
const attributes: Record<string, string> = {}
118133
for (const attr of node.attrs) {
@@ -134,15 +149,38 @@ export function getNodeAssetAttributes(
134149
}
135150

136151
const actions: HtmlAssetAttribute[] = []
137-
function handleAttributeKey(key: string, type: 'src' | 'srcset') {
152+
function handleAttributeKey(
153+
key: string,
154+
type: 'src' | 'srcset',
155+
filter?: (data: HtmlAssetSourceFilterData) => boolean,
156+
) {
138157
const value = attributes[key]
139158
if (!value) return
140-
if (matched.filter && !matched.filter({ key, value, attributes })) return
159+
if (filter && !filter({ key, value, attributes })) return
141160
const location = node.sourceCodeLocation!.attrs![key]
142161
actions.push({ type, key, value, attributes, location })
143162
}
144-
matched.srcAttributes?.forEach((key) => handleAttributeKey(key, 'src'))
145-
matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, 'srcset'))
163+
164+
// Run matching for default asset sources
165+
if (defaults) {
166+
defaults.srcAttributes?.forEach((key) =>
167+
handleAttributeKey(key, 'src', defaults.filter),
168+
)
169+
defaults.srcsetAttributes?.forEach((key) =>
170+
handleAttributeKey(key, 'srcset', defaults.filter),
171+
)
172+
}
173+
174+
// Run matching for additional asset sources
175+
if (additional) {
176+
additional.srcAttributes?.forEach((key) =>
177+
handleAttributeKey(key, 'src', additional.filter),
178+
)
179+
additional.srcsetAttributes?.forEach((key) =>
180+
handleAttributeKey(key, 'srcset', additional.filter),
181+
)
182+
}
183+
146184
return actions
147185
}
148186

‎packages/vite/src/node/config.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ import type { LogLevel, Logger } from './logger'
114114
import { createLogger } from './logger'
115115
import type { DepOptimizationOptions } from './optimizer'
116116
import type { JsonOptions } from './plugins/json'
117+
import type { HtmlAssetSource } from './assetSource'
117118
import type { PackageCache } from './packages'
118119
import { findNearestNodeModules, findNearestPackageData } from './packages'
119120
import { loadEnv, resolveEnvPrefix } from './env'
@@ -542,6 +543,23 @@ export interface HTMLOptions {
542543
* Make sure that this placeholder will be replaced with a unique value for each request by the server.
543544
*/
544545
cspNonce?: string
546+
/**
547+
* Define additional HTML elements and attributes to be treated as asset sources.
548+
* This extends the built-in list that includes standard elements like `<img src>`, `<video src>`, etc.
549+
*
550+
* @example
551+
* ```ts
552+
* html: {
553+
* additionalAssetSources: {
554+
* // Custom web component
555+
* 'html-import': { srcAttributes: ['src'] },
556+
* // Add data-* attributes to existing element
557+
* 'img': { srcAttributes: ['data-src-dark', 'data-src-light'] }
558+
* }
559+
* }
560+
* ```
561+
*/
562+
additionalAssetSources?: Record<string, HtmlAssetSource>
545563
}
546564

547565
export interface FutureOptions {

‎packages/vite/src/node/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ export type {
126126
DevEnvironmentOptions,
127127
ResolvedDevEnvironmentOptions,
128128
} from './config'
129+
export type { HtmlAssetSource } from './assetSource'
129130
export type {
130131
Plugin,
131132
PluginOption,

‎packages/vite/src/node/plugins/html.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
616616

617617
// For asset references in index.html, also generate an import
618618
// statement for each - this will be handled by the asset plugin
619-
const assetAttributes = getNodeAssetAttributes(node)
619+
const assetAttributes = getNodeAssetAttributes(
620+
node,
621+
config.html?.additionalAssetSources,
622+
)
620623
for (const attr of assetAttributes) {
621624
if (attr.type === 'remove') {
622625
s.remove(attr.location.startOffset, attr.location.endOffset)

‎packages/vite/src/node/server/middlewares/indexHtml.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,10 @@ const devHtmlHook: IndexHtmlTransformHook = async (
350350
}
351351

352352
// elements with [href/src] attrs
353-
const assetAttributes = getNodeAssetAttributes(node)
353+
const assetAttributes = getNodeAssetAttributes(
354+
node,
355+
config.html?.additionalAssetSources,
356+
)
354357
for (const attr of assetAttributes) {
355358
if (attr.type === 'remove') {
356359
s.remove(attr.location.startOffset, attr.location.endOffset)

0 commit comments

Comments
 (0)