Skip to content

Commit 2cfe0c0

Browse files
committed
fix: reverts vitejs#8278
This reverts commit 0b25cc1.
1 parent 7d810a9 commit 2cfe0c0

File tree

4 files changed

+45
-19
lines changed

4 files changed

+45
-19
lines changed

packages/vite/src/node/plugins/css.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ const htmlProxyRE = /(\?|&)html-proxy\b/
111111
const commonjsProxyRE = /\?commonjs-proxy/
112112
const inlineRE = /(\?|&)inline\b/
113113
const inlineCSSRE = /(\?|&)inline-css\b/
114+
const usedRE = /(\?|&)used\b/
114115
const varRE = /^var\(/i
115116

116117
const cssBundleName = 'style.css'
@@ -414,19 +415,18 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
414415
}
415416

416417
let code: string
417-
if (modulesCode) {
418-
code = modulesCode
419-
} else {
420-
let content = css
421-
if (config.build.minify) {
422-
content = await minifyCSS(content, config)
418+
if (usedRE.test(id)) {
419+
if (modulesCode) {
420+
code = modulesCode
421+
} else {
422+
let content = css
423+
if (config.build.minify) {
424+
content = await minifyCSS(content, config)
425+
}
426+
code = `export default ${JSON.stringify(content)}`
423427
}
424-
// marking as pure to make it tree-shakable by minifier
425-
// but the module itself is still treated as a non tree-shakable module
426-
// because moduleSideEffects is 'no-treeshake'
427-
code = `export default /* #__PURE__ */ (() => ${JSON.stringify(
428-
content
429-
)})()`
428+
} else {
429+
code = `export default ''`
430430
}
431431

432432
return {

packages/vite/src/node/plugins/importAnalysisBuild.ts

+24-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { OutputChunk, SourceMap } from 'rollup'
66
import colors from 'picocolors'
77
import type { RawSourceMap } from '@ampproject/remapping'
88
import {
9+
bareImportRE,
910
cleanUrl,
1011
combineSourcemaps,
1112
isDataUrl,
@@ -16,7 +17,7 @@ import type { Plugin } from '../plugin'
1617
import type { ResolvedConfig } from '../config'
1718
import { genSourceMapUrl } from '../server/sourcemap'
1819
import { getDepsOptimizer, optimizedDepNeedsInterop } from '../optimizer'
19-
import { removedPureCssFilesCache } from './css'
20+
import { isCSSRequest, removedPureCssFilesCache } from './css'
2021
import { interopNamedImports } from './importAnalysis'
2122

2223
/**
@@ -238,13 +239,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
238239
)
239240
}
240241

241-
if (!depsOptimizer) {
242-
continue
243-
}
244-
245242
// static import or valid string in dynamic import
246243
// If resolvable, let's resolve it
247-
if (specifier) {
244+
if (depsOptimizer && specifier) {
248245
// skip external / data uri
249246
if (isExternalUrl(specifier) || isDataUrl(specifier)) {
250247
continue
@@ -297,6 +294,27 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
297294
}
298295
}
299296
}
297+
298+
// Differentiate CSS imports that use the default export from those that
299+
// do not by injecting a ?used query - this allows us to avoid including
300+
// the CSS string when unnecessary (esbuild has trouble tree-shaking
301+
// them)
302+
if (
303+
specifier &&
304+
isCSSRequest(specifier) &&
305+
// always inject ?used query when it is a dynamic import
306+
// because there is no way to check whether the default export is used
307+
(source.slice(expStart, start).includes('from') || isDynamicImport) &&
308+
// already has ?used query (by import.meta.glob)
309+
!specifier.match(/\?used(&|$)/) &&
310+
// edge case for package names ending with .css (e.g normalize.css)
311+
!(bareImportRE.test(specifier) && !specifier.includes('/'))
312+
) {
313+
const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`)
314+
str().overwrite(start, end, isDynamicImport ? `'${url}'` : url, {
315+
contentOnly: true
316+
})
317+
}
300318
}
301319

302320
if (

packages/vite/src/node/plugins/importMetaGlob.ts

+4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type { ViteDevServer } from '../server'
1818
import type { ModuleNode } from '../server/moduleGraph'
1919
import type { ResolvedConfig } from '../config'
2020
import { normalizePath, slash, transformStableResult } from '../utils'
21+
import { isCSSRequest } from './css'
2122

2223
const { isMatch, scan } = micromatch
2324

@@ -392,6 +393,9 @@ export async function transformGlobImport(
392393
let importPath = paths.importPath
393394
let importQuery = query
394395

396+
if (isCSSRequest(file))
397+
importQuery = importQuery ? `${importQuery}&used` : '?used'
398+
395399
if (importQuery && importQuery !== '?raw') {
396400
const fileExtension = basename(file).split('.').slice(-1)[0]
397401
if (fileExtension && restoreQueryExtension)

playground/css/__tests__/css.spec.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,11 @@ test("relative path rewritten in Less's data-uri", async () => {
429429
test('PostCSS source.input.from includes query', async () => {
430430
const code = await page.textContent('.postcss-source-input')
431431
// should resolve assets
432-
expect(code).toContain('/postcss-source-input.css?query=foo')
432+
expect(code).toContain(
433+
isBuild
434+
? '/postcss-source-input.css?used&query=foo'
435+
: '/postcss-source-input.css?query=foo'
436+
)
433437
})
434438

435439
test('aliased css has content', async () => {

0 commit comments

Comments
 (0)