Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: revert #8278 #8896

Merged
merged 2 commits into from Jul 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 12 additions & 12 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -111,6 +111,7 @@ const htmlProxyRE = /(\?|&)html-proxy\b/
const commonjsProxyRE = /\?commonjs-proxy/
const inlineRE = /(\?|&)inline\b/
const inlineCSSRE = /(\?|&)inline-css\b/
const usedRE = /(\?|&)used\b/
const varRE = /^var\(/i

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

let code: string
if (modulesCode) {
code = modulesCode
} else {
let content = css
if (config.build.minify) {
content = await minifyCSS(content, config)
if (usedRE.test(id)) {
if (modulesCode) {
code = modulesCode
} else {
let content = css
if (config.build.minify) {
content = await minifyCSS(content, config)
}
code = `export default ${JSON.stringify(content)}`
}
// marking as pure to make it tree-shakable by minifier
// but the module itself is still treated as a non tree-shakable module
// because moduleSideEffects is 'no-treeshake'
code = `export default /* #__PURE__ */ (() => ${JSON.stringify(
content
)})()`
} else {
code = `export default ''`
}

return {
Expand Down
30 changes: 24 additions & 6 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -6,6 +6,7 @@ import type { OutputChunk, SourceMap } from 'rollup'
import colors from 'picocolors'
import type { RawSourceMap } from '@ampproject/remapping'
import {
bareImportRE,
cleanUrl,
combineSourcemaps,
isDataUrl,
Expand All @@ -16,7 +17,7 @@ import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
import { genSourceMapUrl } from '../server/sourcemap'
import { getDepsOptimizer, optimizedDepNeedsInterop } from '../optimizer'
import { removedPureCssFilesCache } from './css'
import { isCSSRequest, removedPureCssFilesCache } from './css'
import { interopNamedImports } from './importAnalysis'

/**
Expand Down Expand Up @@ -238,13 +239,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

if (!depsOptimizer) {
continue
}

// static import or valid string in dynamic import
// If resolvable, let's resolve it
if (specifier) {
if (depsOptimizer && specifier) {
// skip external / data uri
if (isExternalUrl(specifier) || isDataUrl(specifier)) {
continue
Expand Down Expand Up @@ -297,6 +294,27 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
}
}
}

// Differentiate CSS imports that use the default export from those that
// do not by injecting a ?used query - this allows us to avoid including
// the CSS string when unnecessary (esbuild has trouble tree-shaking
// them)
if (
specifier &&
isCSSRequest(specifier) &&
// always inject ?used query when it is a dynamic import
// because there is no way to check whether the default export is used
(source.slice(expStart, start).includes('from') || isDynamicImport) &&
// already has ?used query (by import.meta.glob)
!specifier.match(/\?used(&|$)/) &&
// edge case for package names ending with .css (e.g normalize.css)
!(bareImportRE.test(specifier) && !specifier.includes('/'))
) {
const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`)
str().overwrite(start, end, isDynamicImport ? `'${url}'` : url, {
contentOnly: true
})
}
}

if (
Expand Down
4 changes: 4 additions & 0 deletions packages/vite/src/node/plugins/importMetaGlob.ts
Expand Up @@ -18,6 +18,7 @@ import type { ViteDevServer } from '../server'
import type { ModuleNode } from '../server/moduleGraph'
import type { ResolvedConfig } from '../config'
import { normalizePath, slash, transformStableResult } from '../utils'
import { isCSSRequest } from './css'

const { isMatch, scan } = micromatch

Expand Down Expand Up @@ -392,6 +393,9 @@ export async function transformGlobImport(
let importPath = paths.importPath
let importQuery = query

if (isCSSRequest(file))
importQuery = importQuery ? `${importQuery}&used` : '?used'

if (importQuery && importQuery !== '?raw') {
const fileExtension = basename(file).split('.').slice(-1)[0]
if (fileExtension && restoreQueryExtension)
Expand Down
12 changes: 9 additions & 3 deletions playground/css/__tests__/css.spec.ts
Expand Up @@ -349,7 +349,8 @@ test('PostCSS dir-dependency', async () => {
}
})

test('import dependency includes css import', async () => {
// skip because #8278 is reverted
test.skip('import dependency includes css import', async () => {
expect(await getColor('.css-js-dep')).toBe('green')
expect(await getColor('.css-js-dep-module')).toBe('green')
})
Expand Down Expand Up @@ -429,10 +430,15 @@ test("relative path rewritten in Less's data-uri", async () => {
test('PostCSS source.input.from includes query', async () => {
const code = await page.textContent('.postcss-source-input')
// should resolve assets
expect(code).toContain('/postcss-source-input.css?query=foo')
expect(code).toContain(
isBuild
? '/postcss-source-input.css?used&query=foo'
: '/postcss-source-input.css?query=foo'
)
})

test('aliased css has content', async () => {
// skip because #8278 is reverted
test.skip('aliased css has content', async () => {
expect(await getColor('.aliased')).toBe('blue')
expect(await page.textContent('.aliased-content')).toMatch('.aliased')
expect(await getColor('.aliased-module')).toBe('blue')
Expand Down