From 95e1a8c42e50fade87c7f6b6898e0dc135722b75 Mon Sep 17 00:00:00 2001 From: yoho Date: Fri, 22 Apr 2022 23:36:58 +0800 Subject: [PATCH 01/21] fix: style update logic --- packages/vite/src/node/plugins/css.ts | 4 ++-- .../src/node/server/middlewares/indexHtml.ts | 18 +++++++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 83e18aabecdb33..da3bade7a8280a 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -300,6 +300,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { const inlined = inlineRE.test(id) const modules = cssModulesCache.get(config)!.get(id) + const isHTMLProxy = htmlProxyRE.test(id) const modulesCode = modules && dataToEsm(modules, { namedExports: true, preferConst: true }) @@ -311,7 +312,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (options?.ssr) { return modulesCode || `export default ${JSON.stringify(css)}` } - if (inlined) { + if (inlined || isHTMLProxy) { return `export default ${JSON.stringify(css)}` } @@ -346,7 +347,6 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { // and then use the cache replace inline-style-flag when `generateBundle` in vite:build-html plugin const inlineCSS = inlineCSSRE.test(id) const query = parseRequest(id) - const isHTMLProxy = htmlProxyRE.test(id) if (inlineCSS && isHTMLProxy) { addToHTMLProxyTransformResult( `${cleanUrl(id)}_${Number.parseInt(query!.index)}`, diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index ca2538bd9507ed..7a11b0b02ce93f 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -128,13 +128,17 @@ const devHtmlHook: IndexHtmlTransformHook = async ( if (module) { server?.moduleGraph.invalidateModule(module) } - - s.overwrite( - node.loc.start.offset, - node.loc.end.offset, - ``, - { contentOnly: true } - ) + if (ext === 'js') { + s.overwrite( + node.loc.start.offset, + node.loc.end.offset, + ``, + { contentOnly: true } + ) + } else if (ext === 'css') { + // just use the style update hmr don't render css + s.append(``) + } } await traverseHtml(html, htmlPath, (node) => { From d907d41c23566a1f022ad91aab2470a44b49b2b1 Mon Sep 17 00:00:00 2001 From: yoho Date: Sat, 23 Apr 2022 10:41:14 +0800 Subject: [PATCH 02/21] fix: test --- .../css-sourcemap/__tests__/serve.spec.ts | 62 ------------------- 1 file changed, 62 deletions(-) diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 11e33a78af8424..becd792e82293a 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -17,68 +17,6 @@ if (!isBuild) { throw new Error('Not found') } - test('inline css', async () => { - const css = await getStyleTagContentIncluding('.inline ') - const map = extractSourcemap(css) - expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` - Object { - "mappings": "AAGO;AACP,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACf,CAAC,CAAC,CAAC;", - "sources": Array [ - "/root/index.html", - ], - "sourcesContent": Array [ - " - - - - -
-

CSS Sourcemap

- -

<inline>

- -

<linked>: no import

-

<linked>: with import

- -

<imported>: no import

-

<imported>: with import

- -

<imported sass>

-

<imported sass> with module

- -

<imported less> with string additionalData

- -

<imported stylus>

-
- - - - - ", - ], - "version": 3, - } - `) - }) - test('linked css', async () => { const res = await page.request.get( new URL('./linked.css', page.url()).href, From 9ebbc0add149e1c358c714d7dd767fdf16771a9b Mon Sep 17 00:00:00 2001 From: yoho Date: Sat, 23 Apr 2022 12:34:23 +0800 Subject: [PATCH 03/21] feat: update time --- packages/playground/testUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/playground/testUtils.ts b/packages/playground/testUtils.ts index 427fea6d947a4f..ef237d087b6fc8 100644 --- a/packages/playground/testUtils.ts +++ b/packages/playground/testUtils.ts @@ -148,7 +148,7 @@ export async function untilUpdated( expect(actual).toMatch(expected) break } else { - await timeout(50) + await timeout(100) } } } From 683d436ce50c475d0c6dcaa27cfb480d4d447467 Mon Sep 17 00:00:00 2001 From: yoho Date: Sat, 23 Apr 2022 12:37:18 +0800 Subject: [PATCH 04/21] fix: wait for page reload --- packages/playground/assets/__tests__/assets.spec.ts | 6 ++++-- packages/playground/testUtils.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts index 75c0e57952db24..daf6b80a1ccadb 100644 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ b/packages/playground/assets/__tests__/assets.spec.ts @@ -1,4 +1,3 @@ -import { createHash } from 'crypto' import { findAssetFile, getBg, @@ -9,7 +8,8 @@ import { readFile, editFile, notifyRebuildComplete, - untilUpdated + untilUpdated, + timeout } from '../../testUtils' const assetMatch = isBuild @@ -304,6 +304,8 @@ if (!isBuild) { (code) => code.replace('#0088ff', '#00ff88'), true ) + // wait for page reload + await timeout(200) await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)') }) } diff --git a/packages/playground/testUtils.ts b/packages/playground/testUtils.ts index ef237d087b6fc8..6ffefd6c2b1291 100644 --- a/packages/playground/testUtils.ts +++ b/packages/playground/testUtils.ts @@ -63,7 +63,7 @@ function rgbToHex(rgb: string): string { } } -const timeout = (n: number) => new Promise((r) => setTimeout(r, n)) +export const timeout = (n: number) => new Promise((r) => setTimeout(r, n)) async function toEl(el: string | ElementHandle): Promise { if (typeof el === 'string') { @@ -148,7 +148,7 @@ export async function untilUpdated( expect(actual).toMatch(expected) break } else { - await timeout(100) + await timeout(50) } } } From 05ab9068476127b0f96bcb06bef3d8966cf27493 Mon Sep 17 00:00:00 2001 From: yoho Date: Tue, 26 Apr 2022 22:33:41 +0800 Subject: [PATCH 05/21] feat: ssr html test --- packages/playground/ssr-html/index.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/playground/ssr-html/index.html b/packages/playground/ssr-html/index.html index c37dcc7e366ae8..995c828caae1a8 100644 --- a/packages/playground/ssr-html/index.html +++ b/packages/playground/ssr-html/index.html @@ -4,6 +4,11 @@ SSR HTML +

SSR Dynamic HTML

From 6bae2a3818a530ae23858c233a4a8858ac26fe60 Mon Sep 17 00:00:00 2001 From: yoho <907415276@qq.com> Date: Wed, 27 Apr 2022 09:57:04 +0800 Subject: [PATCH 06/21] fix: timeout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 翠 / green --- packages/playground/assets/__tests__/assets.spec.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts index daf6b80a1ccadb..9104e030923829 100644 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ b/packages/playground/assets/__tests__/assets.spec.ts @@ -304,8 +304,7 @@ if (!isBuild) { (code) => code.replace('#0088ff', '#00ff88'), true ) - // wait for page reload - await timeout(200) + await page.waitForNavigation() await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)') }) } From c481f26892e5da678d0232a86cbc79fa69ffc674 Mon Sep 17 00:00:00 2001 From: yoho Date: Wed, 27 Apr 2022 12:27:08 +0800 Subject: [PATCH 07/21] feat: style assert --- packages/playground/assets/__tests__/assets.spec.ts | 8 ++++++-- packages/playground/assets/index.html | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts index 9104e030923829..19dd52f71e114a 100644 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ b/packages/playground/assets/__tests__/assets.spec.ts @@ -8,8 +8,7 @@ import { readFile, editFile, notifyRebuildComplete, - untilUpdated, - timeout + untilUpdated } from '../../testUtils' const assetMatch = isBuild @@ -296,6 +295,11 @@ describe('css and assets in css in build watch', () => { } }) +test('inline style test', async () => { + expect(await getBg('.inline-style')).toMatch(assetMatch) + expect(await getBg('.style-url-assets')).toMatch(assetMatch) +}) + if (!isBuild) { test('@import in html style tag hmr', async () => { await untilUpdated(() => getColor('.import-css'), 'rgb(0, 136, 255)') diff --git a/packages/playground/assets/index.html b/packages/playground/assets/index.html index 6678a2da7c2106..7f936f467eeb0e 100644 --- a/packages/playground/assets/index.html +++ b/packages/playground/assets/index.html @@ -207,7 +207,10 @@

url

background-size: 10px 10px; } -
+
inline style
use style class
From 31003474a69d19826fe89b357a655c63eafe5639 Mon Sep 17 00:00:00 2001 From: yoho Date: Wed, 27 Apr 2022 23:21:36 +0800 Subject: [PATCH 08/21] test: relative path --- packages/playground/hmr/__tests__/hmr.spec.ts | 22 +++++++++++++----- packages/playground/hmr/icon.png | Bin 0 -> 3395 bytes packages/playground/hmr/index.html | 9 +++++++ 3 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 packages/playground/hmr/icon.png diff --git a/packages/playground/hmr/__tests__/hmr.spec.ts b/packages/playground/hmr/__tests__/hmr.spec.ts index 7325c9fe47943a..3b6237dbb110bc 100644 --- a/packages/playground/hmr/__tests__/hmr.spec.ts +++ b/packages/playground/hmr/__tests__/hmr.spec.ts @@ -1,4 +1,4 @@ -import { isBuild, editFile, untilUpdated } from '../../testUtils' +import { isBuild, editFile, untilUpdated, getBg } from '../../testUtils' test('should render', async () => { expect(await page.textContent('.app')).toBe('1') @@ -13,6 +13,18 @@ if (!isBuild) { browserLogs.length = 0 }) + test('css in html hmr', async () => { + expect(await getBg('.import-image')).toMatch('icon') + // test relative path + await (viteTestUrl + '/foo/') + expect(await getBg('.import-image')).toMatch('icon') + await page.goto(viteTestUrl) + editFile('dynamic-import/dep.ts', (code) => + code.replace('url("./icon.png")', '') + ) + expect(await getBg('.import-image')).toMatch('') + }) + test('self accept', async () => { const el = await page.$('.app') @@ -129,9 +141,7 @@ if (!isBuild) { }) test('full-reload encodeURI path', async () => { - await page.goto( - viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html' - ) + await (viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html') const el = await page.$('#app') expect(await el.textContent()).toBe('title') await editFile( @@ -146,7 +156,7 @@ if (!isBuild) { }) test('CSS update preserves query params', async () => { - await page.goto(viteTestUrl) + await viteTestUrl editFile('global.css', (code) => code.replace('white', 'tomato')) @@ -162,7 +172,7 @@ if (!isBuild) { }) test('not loaded dynamic import', async () => { - await page.goto(viteTestUrl + '/dynamic-import/index.html') + await (viteTestUrl + '/dynamic-import/index.html') let btn = await page.$('button') expect(await btn.textContent()).toBe('Counter 0') diff --git a/packages/playground/hmr/icon.png b/packages/playground/hmr/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..4388bfdca3d4d778d2f25a5861599f8f19a1177c GIT binary patch literal 3395 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 literal 0 HcmV?d00001 diff --git a/packages/playground/hmr/index.html b/packages/playground/hmr/index.html index 0add7c26011a01..65a2ed381b027a 100644 --- a/packages/playground/hmr/index.html +++ b/packages/playground/hmr/index.html @@ -1,5 +1,13 @@ +
@@ -8,3 +16,4 @@
+
From d0902ae69f0831e679521e7ddf88d1cfcdfdd893 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 12:46:26 +0800 Subject: [PATCH 09/21] fix: replace css intime --- packages/vite/src/node/plugins/css.ts | 24 +++++++++++++++++++ .../src/node/server/middlewares/indexHtml.ts | 22 ++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index da3bade7a8280a..e6b2f5834b5e7c 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -21,6 +21,7 @@ import type { ExistingRawSourceMap, NormalizedOutputOptions, OutputChunk, + PluginContext, RenderedChunk, RollupError, SourceMapInput @@ -614,6 +615,29 @@ function getCssResolversKeys( return Object.keys(resolvers) as unknown as Array } +export function createCSSCompiler(config: ResolvedConfig, ctx: PluginContext) { + const resolveUrl = config.createResolver({ + preferRelative: true, + tryIndex: false, + extensions: [] + }) + const atImportResolvers = createCSSResolvers(config) + + const urlReplacer: CssUrlReplacer = async (url, importer) => { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1) + } + const resolved = await resolveUrl(url, importer) + if (resolved) { + return fileToUrl(resolved, config, ctx) + } + return url + } + + return (id: string, code: string) => + compileCSS(id, code, config, urlReplacer, atImportResolvers) +} + async function compileCSS( id: string, code: string, diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 7a11b0b02ce93f..f4c81ed6f88db6 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -18,12 +18,18 @@ import { send } from '../send' import { CLIENT_PUBLIC_PATH, FS_PREFIX } from '../../constants' import { cleanUrl, fsPathFromId, normalizePath, injectQuery } from '../../utils' import type { ModuleGraph } from '../moduleGraph' +import { createCSSCompiler } from '../../plugins/css' + +interface AssetNode { + start: number + end: number + code: string +} export function createDevHtmlTransformFn( server: ViteDevServer ): (url: string, html: string, originalUrl: string) => Promise { const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins) - return (url: string, html: string, originalUrl: string): Promise => { return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], { path: url, @@ -94,12 +100,15 @@ const devHtmlHook: IndexHtmlTransformHook = async ( html, { path: htmlPath, filename, server, originalUrl } ) => { + // css compile need to emitFile in build mode, and serve mode is not need. + const compileCSS = createCSSCompiler(server!.config, null as any) const { config, moduleGraph } = server! const base = config.base || '/' const s = new MagicString(html) let inlineModuleIndex = -1 const filePath = cleanUrl(htmlPath) + const styleUrl: AssetNode[] = [] const addInlineModule = (node: ElementNode, ext: 'js' | 'css') => { inlineModuleIndex++ @@ -158,6 +167,12 @@ const devHtmlHook: IndexHtmlTransformHook = async ( } if (node.tag === 'style' && node.children.length) { + const children = node.children[0] as TextNode + styleUrl.push({ + start: children.loc.start.offset, + end: children.loc.end.offset, + code: children.content + }) addInlineModule(node, 'css') } @@ -176,6 +191,11 @@ const devHtmlHook: IndexHtmlTransformHook = async ( } }) + for (const { start, end, code } of styleUrl) { + const compliedCode = await compileCSS(filename + '.css', code) + s.overwrite(start, end, compliedCode.code) + } + html = s.toString() return { From 8c6127f8bcc41ee757ca2a11b83eee9a78c92000 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 16:28:31 +0800 Subject: [PATCH 10/21] fix: public css, revert #7031 --- packages/vite/src/node/plugins/css.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index e6b2f5834b5e7c..2bfec01237b119 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -741,12 +741,11 @@ async function compileCSS( postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [] if (needInlineImport) { - const isHTMLProxy = htmlProxyRE.test(id) postcssPlugins.unshift( (await import('postcss-import')).default({ async resolve(id, basedir) { const publicFile = checkPublicFile(id, config) - if (isHTMLProxy && publicFile) { + if (publicFile) { return publicFile } From 0010faec6437b0ccef5cbc12f12606d5b459af32 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 17:07:33 +0800 Subject: [PATCH 11/21] fix: hmr test --- packages/playground/hmr/__tests__/hmr.spec.ts | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/packages/playground/hmr/__tests__/hmr.spec.ts b/packages/playground/hmr/__tests__/hmr.spec.ts index c02c4c84a71f42..b323069d11ed5a 100644 --- a/packages/playground/hmr/__tests__/hmr.spec.ts +++ b/packages/playground/hmr/__tests__/hmr.spec.ts @@ -13,18 +13,6 @@ if (!isBuild) { browserLogs.length = 0 }) - test('css in html hmr', async () => { - expect(await getBg('.import-image')).toMatch('icon') - // test relative path - await (viteTestUrl + '/foo/') - expect(await getBg('.import-image')).toMatch('icon') - await page.goto(viteTestUrl) - editFile('dynamic-import/dep.ts', (code) => - code.replace('url("./icon.png")', '') - ) - expect(await getBg('.import-image')).toMatch('') - }) - test('self accept', async () => { const el = await page.$('.app') @@ -141,7 +129,9 @@ if (!isBuild) { }) test('full-reload encodeURI path', async () => { - await (viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html') + await page.goto( + viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html' + ) const el = await page.$('#app') expect(await el.textContent()).toBe('title') await editFile( @@ -156,7 +146,7 @@ if (!isBuild) { }) test('CSS update preserves query params', async () => { - await viteTestUrl + await page.goto(viteTestUrl) editFile('global.css', (code) => code.replace('white', 'tomato')) @@ -205,6 +195,15 @@ if (!isBuild) { expect(await btn.textContent()).toBe('Counter 1') }) + test('css in html hmr', async () => { + await page.goto(viteTestUrl) + expect(await getBg('.import-image')).toMatch('icon') + await page.goto(viteTestUrl + '/foo/') + expect(await getBg('.import-image')).toMatch('icon') + editFile('index.html', (code) => code.replace('url("./icon.png")', '')) + expect(await getBg('.import-image')).toMatch('') + }) + test('HTML', async () => { await page.goto(viteTestUrl + '/counter/index.html') let btn = await page.$('button') From d55f11ae0bfd71cef3bfaae4e3277d6e9c058fdd Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 19:12:23 +0800 Subject: [PATCH 12/21] fix: test --- packages/playground/hmr/__tests__/hmr.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/playground/hmr/__tests__/hmr.spec.ts b/packages/playground/hmr/__tests__/hmr.spec.ts index b323069d11ed5a..34612ee1e7d3d5 100644 --- a/packages/playground/hmr/__tests__/hmr.spec.ts +++ b/packages/playground/hmr/__tests__/hmr.spec.ts @@ -201,6 +201,7 @@ if (!isBuild) { await page.goto(viteTestUrl + '/foo/') expect(await getBg('.import-image')).toMatch('icon') editFile('index.html', (code) => code.replace('url("./icon.png")', '')) + await page.waitForNavigation() expect(await getBg('.import-image')).toMatch('') }) From 8aca36b829d2b17a58edaaf2c067e795a03a59bc Mon Sep 17 00:00:00 2001 From: yoho <907415276@qq.com> Date: Thu, 28 Apr 2022 20:40:14 +0800 Subject: [PATCH 13/21] chore: remove unused export Co-authored-by: patak --- packages/playground/testUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/playground/testUtils.ts b/packages/playground/testUtils.ts index 6ffefd6c2b1291..427fea6d947a4f 100644 --- a/packages/playground/testUtils.ts +++ b/packages/playground/testUtils.ts @@ -63,7 +63,7 @@ function rgbToHex(rgb: string): string { } } -export const timeout = (n: number) => new Promise((r) => setTimeout(r, n)) +const timeout = (n: number) => new Promise((r) => setTimeout(r, n)) async function toEl(el: string | ElementHandle): Promise { if (typeof el === 'string') { From 0ef0a62ae634b5ae6393d74f993ba26cf2870a31 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 21:01:57 +0800 Subject: [PATCH 14/21] feat: svg style tests --- packages/playground/assets/index.html | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/playground/assets/index.html b/packages/playground/assets/index.html index 7f936f467eeb0e..99c2c2fe69ae70 100644 --- a/packages/playground/assets/index.html +++ b/packages/playground/assets/index.html @@ -238,6 +238,21 @@

import module css

+

style in svg

+ + + + + + + + From 43c3dce37e268e5208075c66db07f9fe70395758 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 21:30:30 +0800 Subject: [PATCH 15/21] feat: `createCSSCompiler` support add hmr deps --- packages/vite/src/node/plugins/css.ts | 185 +++++++++--------- .../src/node/server/middlewares/indexHtml.ts | 26 +-- 2 files changed, 98 insertions(+), 113 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 2bfec01237b119..d47da5489e95c5 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -94,6 +94,20 @@ export interface CSSModulesOptions { | null } +interface CompileCSSResult { + code: string + map?: SourceMapInput + ast?: PostCSS.Result + modules?: Record + deps?: Set +} + +type CSSCompiler = ( + id: string, + raw: string, + ssr?: boolean +) => Promise + const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)` const cssLangRE = new RegExp(cssLangs) const cssModuleRE = new RegExp(`\\.module${cssLangs}`) @@ -146,13 +160,7 @@ const postcssConfigCache = new WeakMap< export function cssPlugin(config: ResolvedConfig): Plugin { let server: ViteDevServer let moduleCache: Map> - - const resolveUrl = config.createResolver({ - preferRelative: true, - tryIndex: false, - extensions: [] - }) - const atImportResolvers = createCSSResolvers(config) + let cssCompiler: CSSCompiler return { name: 'vite:css', @@ -177,87 +185,9 @@ export function cssPlugin(config: ResolvedConfig): Plugin { ) { return } + cssCompiler ||= createCSSCompiler(config, this, server) const ssr = options?.ssr === true - - const urlReplacer: CssUrlReplacer = async (url, importer) => { - if (checkPublicFile(url, config)) { - return config.base + url.slice(1) - } - const resolved = await resolveUrl(url, importer) - if (resolved) { - return fileToUrl(resolved, config, this) - } - return url - } - - const { - code: css, - modules, - deps, - map - } = await compileCSS( - id, - raw, - config, - urlReplacer, - atImportResolvers, - server - ) - if (modules) { - moduleCache.set(id, modules) - } - - // track deps for build watch mode - if (config.command === 'build' && config.build.watch && deps) { - for (const file of deps) { - this.addWatchFile(file) - } - } - - // dev - if (server) { - // server only logic for handling CSS @import dependency hmr - const { moduleGraph } = server - const thisModule = moduleGraph.getModuleById(id) - if (thisModule) { - // CSS modules cannot self-accept since it exports values - const isSelfAccepting = !modules && !inlineRE.test(id) - if (deps) { - // record deps in the module graph so edits to @import css can trigger - // main import to hot update - const depModules = new Set() - for (const file of deps) { - depModules.add( - isCSSRequest(file) - ? moduleGraph.createFileOnlyEntry(file) - : await moduleGraph.ensureEntryFromUrl( - ( - await fileToUrl(file, config, this) - ).replace( - (config.server?.origin ?? '') + config.base, - '/' - ), - ssr - ) - ) - } - moduleGraph.updateModuleInfo( - thisModule, - depModules, - // The root CSS proxy module is self-accepting and should not - // have an explicit accept list - new Set(), - isSelfAccepting, - ssr - ) - for (const file of deps) { - this.addWatchFile(file) - } - } else { - thisModule.isSelfAccepting = isSelfAccepting - } - } - } + const { code: css, map } = await cssCompiler(id, raw, ssr) return { code: css, @@ -615,7 +545,11 @@ function getCssResolversKeys( return Object.keys(resolvers) as unknown as Array } -export function createCSSCompiler(config: ResolvedConfig, ctx: PluginContext) { +export function createCSSCompiler( + config: ResolvedConfig, + ctx: PluginContext, + server?: ViteDevServer +): CSSCompiler { const resolveUrl = config.createResolver({ preferRelative: true, tryIndex: false, @@ -634,8 +568,71 @@ export function createCSSCompiler(config: ResolvedConfig, ctx: PluginContext) { return url } - return (id: string, code: string) => - compileCSS(id, code, config, urlReplacer, atImportResolvers) + return async (id: string, raw: string, ssr?: boolean) => { + const compiledResult = await compileCSS( + id, + raw, + config, + urlReplacer, + atImportResolvers, + server + ) + const { modules, deps } = compiledResult + if (modules) { + cssModulesCache.get(config)?.set(id, modules) + } + + // track deps for build watch mode + if (config.command === 'build' && config.build.watch && deps) { + for (const file of deps) { + ctx.addWatchFile(file) + } + } + + // dev + if (server) { + // server only logic for handling CSS @import dependency hmr + const { moduleGraph } = server + const thisModule = moduleGraph.getModuleById(id) + if (thisModule) { + // CSS modules cannot self-accept since it exports values + const isSelfAccepting = !modules && !inlineRE.test(id) + if (deps) { + // record deps in the module graph so edits to @import css can trigger + // main import to hot update + const depModules = new Set() + for (const file of deps) { + depModules.add( + isCSSRequest(file) + ? moduleGraph.createFileOnlyEntry(file) + : await moduleGraph.ensureEntryFromUrl( + ( + await fileToUrl(file, config, ctx) + ).replace((config.server?.origin ?? '') + config.base, '/'), + ssr + ) + ) + } + moduleGraph.updateModuleInfo( + thisModule, + depModules, + // The root CSS proxy module is self-accepting and should not + // have an explicit accept list + new Set(), + isSelfAccepting, + ssr + ) + for (const file of deps) { + ctx.addWatchFile(file) + } + } else { + thisModule.isSelfAccepting = isSelfAccepting + } + } + } + + return compiledResult + } } async function compileCSS( @@ -645,13 +642,7 @@ async function compileCSS( urlReplacer: CssUrlReplacer, atImportResolvers: CSSAtImportResolvers, server?: ViteDevServer -): Promise<{ - code: string - map?: SourceMapInput - ast?: PostCSS.Result - modules?: Record - deps?: Set -}> { +): Promise { const { modules: modulesOptions, preprocessorOptions, diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index f4c81ed6f88db6..689b5d0cb046b4 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -101,7 +101,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( { path: htmlPath, filename, server, originalUrl } ) => { // css compile need to emitFile in build mode, and serve mode is not need. - const compileCSS = createCSSCompiler(server!.config, null as any) + const compileCSS = createCSSCompiler(server!.config, null as any, server) const { config, moduleGraph } = server! const base = config.base || '/' @@ -110,7 +110,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( const filePath = cleanUrl(htmlPath) const styleUrl: AssetNode[] = [] - const addInlineModule = (node: ElementNode, ext: 'js' | 'css') => { + const addInlineModule = (node: ElementNode, ext: 'js') => { inlineModuleIndex++ const url = filePath.replace(normalizePath(config.root), '') @@ -137,17 +137,12 @@ const devHtmlHook: IndexHtmlTransformHook = async ( if (module) { server?.moduleGraph.invalidateModule(module) } - if (ext === 'js') { - s.overwrite( - node.loc.start.offset, - node.loc.end.offset, - ``, - { contentOnly: true } - ) - } else if (ext === 'css') { - // just use the style update hmr don't render css - s.append(``) - } + s.overwrite( + node.loc.start.offset, + node.loc.end.offset, + ``, + { contentOnly: true } + ) } await traverseHtml(html, htmlPath, (node) => { @@ -173,7 +168,6 @@ const devHtmlHook: IndexHtmlTransformHook = async ( end: children.loc.end.offset, code: children.content }) - addInlineModule(node, 'css') } // elements with [href/src] attrs @@ -192,8 +186,8 @@ const devHtmlHook: IndexHtmlTransformHook = async ( }) for (const { start, end, code } of styleUrl) { - const compliedCode = await compileCSS(filename + '.css', code) - s.overwrite(start, end, compliedCode.code) + const complied = await compileCSS(filename + '.css', code) + s.overwrite(start, end, complied.code) } html = s.toString() From 68c14dcc2ba5746b2d83398441124f442216c691 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 23:17:55 +0800 Subject: [PATCH 16/21] feat: ensureWatchedFile inline css --- packages/vite/src/node/plugins/css.ts | 9 ++++--- .../src/node/server/middlewares/indexHtml.ts | 26 +++++++++++++------ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index d47da5489e95c5..15213dedba005c 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -243,10 +243,12 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (options?.ssr) { return modulesCode || `export default ${JSON.stringify(css)}` } - if (inlined || isHTMLProxy) { + if (inlined) { return `export default ${JSON.stringify(css)}` } - + if (isHTMLProxy) { + return css + } let cssContent = css if (config.css?.devSourcemap) { const sourcemap = this.getCombinedSourcemap() @@ -567,6 +569,7 @@ export function createCSSCompiler( } return url } + const moduleCache = cssModulesCache.get(config)! return async (id: string, raw: string, ssr?: boolean) => { const compiledResult = await compileCSS( @@ -579,7 +582,7 @@ export function createCSSCompiler( ) const { modules, deps } = compiledResult if (modules) { - cssModulesCache.get(config)?.set(id, modules) + moduleCache.set(id, modules) } // track deps for build watch mode diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 689b5d0cb046b4..4743516bfeaa68 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -16,9 +16,14 @@ import { import type { ResolvedConfig, ViteDevServer } from '../..' import { send } from '../send' import { CLIENT_PUBLIC_PATH, FS_PREFIX } from '../../constants' -import { cleanUrl, fsPathFromId, normalizePath, injectQuery } from '../../utils' +import { + cleanUrl, + fsPathFromId, + normalizePath, + injectQuery, + ensureWatchedFile +} from '../../utils' import type { ModuleGraph } from '../moduleGraph' -import { createCSSCompiler } from '../../plugins/css' interface AssetNode { start: number @@ -100,9 +105,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( html, { path: htmlPath, filename, server, originalUrl } ) => { - // css compile need to emitFile in build mode, and serve mode is not need. - const compileCSS = createCSSCompiler(server!.config, null as any, server) - const { config, moduleGraph } = server! + const { config, moduleGraph, watcher } = server! const base = config.base || '/' const s = new MagicString(html) @@ -185,9 +188,16 @@ const devHtmlHook: IndexHtmlTransformHook = async ( } }) - for (const { start, end, code } of styleUrl) { - const complied = await compileCSS(filename + '.css', code) - s.overwrite(start, end, complied.code) + for (let index = 0; index < styleUrl.length; index++) { + const { start, end, code } = styleUrl[index] + const url = filename + `?html-proxy&${index}.css` + + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url, false) + ensureWatchedFile(watcher, mod.file, config.root) + + const result = await server!.pluginContainer.transform(code, url) + s.overwrite(start, end, result?.code || '') } html = s.toString() From 8a6c853e0a34c0250209b54abc17518c8f88c6eb Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 23:21:48 +0800 Subject: [PATCH 17/21] chore: remove `createCSSCompiler` --- packages/vite/src/node/plugins/css.ts | 181 +++++++++++++------------- 1 file changed, 87 insertions(+), 94 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 15213dedba005c..ab763c46ddc048 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -160,7 +160,13 @@ const postcssConfigCache = new WeakMap< export function cssPlugin(config: ResolvedConfig): Plugin { let server: ViteDevServer let moduleCache: Map> - let cssCompiler: CSSCompiler + + const resolveUrl = config.createResolver({ + preferRelative: true, + tryIndex: false, + extensions: [] + }) + const atImportResolvers = createCSSResolvers(config) return { name: 'vite:css', @@ -185,9 +191,87 @@ export function cssPlugin(config: ResolvedConfig): Plugin { ) { return } - cssCompiler ||= createCSSCompiler(config, this, server) const ssr = options?.ssr === true - const { code: css, map } = await cssCompiler(id, raw, ssr) + + const urlReplacer: CssUrlReplacer = async (url, importer) => { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1) + } + const resolved = await resolveUrl(url, importer) + if (resolved) { + return fileToUrl(resolved, config, this) + } + return url + } + + const { + code: css, + modules, + deps, + map + } = await compileCSS( + id, + raw, + config, + urlReplacer, + atImportResolvers, + server + ) + if (modules) { + moduleCache.set(id, modules) + } + + // track deps for build watch mode + if (config.command === 'build' && config.build.watch && deps) { + for (const file of deps) { + this.addWatchFile(file) + } + } + + // dev + if (server) { + // server only logic for handling CSS @import dependency hmr + const { moduleGraph } = server + const thisModule = moduleGraph.getModuleById(id) + if (thisModule) { + // CSS modules cannot self-accept since it exports values + const isSelfAccepting = !modules && !inlineRE.test(id) + if (deps) { + // record deps in the module graph so edits to @import css can trigger + // main import to hot update + const depModules = new Set() + for (const file of deps) { + depModules.add( + isCSSRequest(file) + ? moduleGraph.createFileOnlyEntry(file) + : await moduleGraph.ensureEntryFromUrl( + ( + await fileToUrl(file, config, this) + ).replace( + (config.server?.origin ?? '') + config.base, + '/' + ), + ssr + ) + ) + } + moduleGraph.updateModuleInfo( + thisModule, + depModules, + // The root CSS proxy module is self-accepting and should not + // have an explicit accept list + new Set(), + isSelfAccepting, + ssr + ) + for (const file of deps) { + this.addWatchFile(file) + } + } else { + thisModule.isSelfAccepting = isSelfAccepting + } + } + } return { code: css, @@ -547,97 +631,6 @@ function getCssResolversKeys( return Object.keys(resolvers) as unknown as Array } -export function createCSSCompiler( - config: ResolvedConfig, - ctx: PluginContext, - server?: ViteDevServer -): CSSCompiler { - const resolveUrl = config.createResolver({ - preferRelative: true, - tryIndex: false, - extensions: [] - }) - const atImportResolvers = createCSSResolvers(config) - - const urlReplacer: CssUrlReplacer = async (url, importer) => { - if (checkPublicFile(url, config)) { - return config.base + url.slice(1) - } - const resolved = await resolveUrl(url, importer) - if (resolved) { - return fileToUrl(resolved, config, ctx) - } - return url - } - const moduleCache = cssModulesCache.get(config)! - - return async (id: string, raw: string, ssr?: boolean) => { - const compiledResult = await compileCSS( - id, - raw, - config, - urlReplacer, - atImportResolvers, - server - ) - const { modules, deps } = compiledResult - if (modules) { - moduleCache.set(id, modules) - } - - // track deps for build watch mode - if (config.command === 'build' && config.build.watch && deps) { - for (const file of deps) { - ctx.addWatchFile(file) - } - } - - // dev - if (server) { - // server only logic for handling CSS @import dependency hmr - const { moduleGraph } = server - const thisModule = moduleGraph.getModuleById(id) - if (thisModule) { - // CSS modules cannot self-accept since it exports values - const isSelfAccepting = !modules && !inlineRE.test(id) - if (deps) { - // record deps in the module graph so edits to @import css can trigger - // main import to hot update - const depModules = new Set() - for (const file of deps) { - depModules.add( - isCSSRequest(file) - ? moduleGraph.createFileOnlyEntry(file) - : await moduleGraph.ensureEntryFromUrl( - ( - await fileToUrl(file, config, ctx) - ).replace((config.server?.origin ?? '') + config.base, '/'), - ssr - ) - ) - } - moduleGraph.updateModuleInfo( - thisModule, - depModules, - // The root CSS proxy module is self-accepting and should not - // have an explicit accept list - new Set(), - isSelfAccepting, - ssr - ) - for (const file of deps) { - ctx.addWatchFile(file) - } - } else { - thisModule.isSelfAccepting = isSelfAccepting - } - } - } - - return compiledResult - } -} - async function compileCSS( id: string, code: string, From 57b936bcb654440755d3b64b6088b33754e72fc7 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 23:23:30 +0800 Subject: [PATCH 18/21] chore: remove useless code --- packages/vite/src/node/plugins/css.ts | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index ab763c46ddc048..03c7dd61f2f820 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -94,20 +94,6 @@ export interface CSSModulesOptions { | null } -interface CompileCSSResult { - code: string - map?: SourceMapInput - ast?: PostCSS.Result - modules?: Record - deps?: Set -} - -type CSSCompiler = ( - id: string, - raw: string, - ssr?: boolean -) => Promise - const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)` const cssLangRE = new RegExp(cssLangs) const cssModuleRE = new RegExp(`\\.module${cssLangs}`) @@ -638,7 +624,13 @@ async function compileCSS( urlReplacer: CssUrlReplacer, atImportResolvers: CSSAtImportResolvers, server?: ViteDevServer -): Promise { +): Promise<{ + code: string + map?: SourceMapInput + ast?: PostCSS.Result + modules?: Record + deps?: Set +}> { const { modules: modulesOptions, preprocessorOptions, From a5e785594a138cb0585e05ddfcbddce2ee826da0 Mon Sep 17 00:00:00 2001 From: yoho Date: Thu, 28 Apr 2022 23:25:58 +0800 Subject: [PATCH 19/21] chore: types --- packages/vite/src/node/plugins/css.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 03c7dd61f2f820..c753e644387c69 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -21,7 +21,6 @@ import type { ExistingRawSourceMap, NormalizedOutputOptions, OutputChunk, - PluginContext, RenderedChunk, RollupError, SourceMapInput From c30793c82e2124bd656adecdad3a69156f4bcc5d Mon Sep 17 00:00:00 2001 From: yoho Date: Fri, 29 Apr 2022 08:23:42 +0800 Subject: [PATCH 20/21] perf: promise.all --- .../src/node/server/middlewares/indexHtml.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 4743516bfeaa68..8638492b1c2001 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -188,17 +188,18 @@ const devHtmlHook: IndexHtmlTransformHook = async ( } }) - for (let index = 0; index < styleUrl.length; index++) { - const { start, end, code } = styleUrl[index] - const url = filename + `?html-proxy&${index}.css` + await Promise.all( + styleUrl.map(async ({ start, end, code }, index) => { + const url = filename + `?html-proxy&${index}.css` - // ensure module in graph after successful load - const mod = await moduleGraph.ensureEntryFromUrl(url, false) - ensureWatchedFile(watcher, mod.file, config.root) + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url, false) + ensureWatchedFile(watcher, mod.file, config.root) - const result = await server!.pluginContainer.transform(code, url) - s.overwrite(start, end, result?.code || '') - } + const result = await server!.pluginContainer.transform(code, url) + s.overwrite(start, end, result?.code || '') + }) + ) html = s.toString() From 13c33edc0911e20f065d1a2cd33d2491ec56ca07 Mon Sep 17 00:00:00 2001 From: yoho Date: Sat, 30 Apr 2022 11:03:45 +0800 Subject: [PATCH 21/21] feat: css content add sourcemap --- packages/vite/src/node/plugins/css.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index c753e644387c69..7a9e473b2d2079 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -315,9 +315,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (inlined) { return `export default ${JSON.stringify(css)}` } - if (isHTMLProxy) { - return css - } + let cssContent = css if (config.css?.devSourcemap) { const sourcemap = this.getCombinedSourcemap() @@ -325,6 +323,10 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { cssContent = getCodeWithSourcemap('css', css, sourcemap) } + if (isHTMLProxy) { + return cssContent + } + return [ `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify( path.posix.join(config.base, CLIENT_PUBLIC_PATH)