From 8a7af50b5ddf72f21098406e9668bc609b323899 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Thu, 31 Oct 2024 15:57:16 +0800 Subject: [PATCH] feat(html)!: support more asset sources (#11138) --- docs/guide/features.md | 22 ++- .../src/node/__tests__/assetSource.spec.ts | 97 ++++++++++ packages/vite/src/node/assetSource.ts | 151 +++++++++++++++ packages/vite/src/node/plugins/html.ts | 178 +++++++----------- .../src/node/server/middlewares/indexHtml.ts | 46 ++--- playground/assets/__tests__/assets.spec.ts | 12 ++ playground/assets/index.html | 5 + 7 files changed, 369 insertions(+), 142 deletions(-) create mode 100644 packages/vite/src/node/__tests__/assetSource.spec.ts create mode 100644 packages/vite/src/node/assetSource.ts diff --git a/docs/guide/features.md b/docs/guide/features.md index ea5855ab9ba368..30b0ad7456ce8a 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -170,9 +170,24 @@ Any HTML files in your project root can be directly accessed by its respective d - `/about.html` -> `http://localhost:5173/about.html` - `/blog/index.html` -> `http://localhost:5173/blog/index.html` -HTML elements such as ` diff --git a/packages/vite/src/node/__tests__/assetSource.spec.ts b/packages/vite/src/node/__tests__/assetSource.spec.ts new file mode 100644 index 00000000000000..2c05d90e57b265 --- /dev/null +++ b/packages/vite/src/node/__tests__/assetSource.spec.ts @@ -0,0 +1,97 @@ +import { describe, expect, test } from 'vitest' +import { type DefaultTreeAdapterMap, parseFragment } from 'parse5' +import { getNodeAssetAttributes } from '../assetSource' + +describe('getNodeAssetAttributes', () => { + const getNode = (html: string) => { + const ast = parseFragment(html, { sourceCodeLocationInfo: true }) + return ast.childNodes[0] as DefaultTreeAdapterMap['element'] + } + + test('handles img src', () => { + const node = getNode('') + const attrs = getNodeAssetAttributes(node) + expect(attrs).toHaveLength(1) + expect(attrs[0]).toHaveProperty('type', 'src') + expect(attrs[0]).toHaveProperty('key', 'src') + expect(attrs[0]).toHaveProperty('value', 'foo.jpg') + expect(attrs[0].attributes).toEqual({ src: 'foo.jpg' }) + expect(attrs[0].location).toHaveProperty('startOffset', 5) + expect(attrs[0].location).toHaveProperty('endOffset', 18) + }) + + test('handles source srcset', () => { + const node = getNode('') + const attrs = getNodeAssetAttributes(node) + expect(attrs).toHaveLength(1) + expect(attrs[0]).toHaveProperty('type', 'srcset') + expect(attrs[0]).toHaveProperty('key', 'srcset') + expect(attrs[0]).toHaveProperty('value', 'foo.jpg 1x, bar.jpg 2x') + expect(attrs[0].attributes).toEqual({ srcset: 'foo.jpg 1x, bar.jpg 2x' }) + }) + + test('handles video src and poster', () => { + const node = getNode('