Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/vite/src/node/__tests__/plugins/css.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import { describe, expect, onTestFinished, test } from 'vitest'
import type { InternalModuleFormat } from 'rolldown'
import MagicString from 'magic-string'
import { resolveConfig } from '../../config'
import type { InlineConfig } from '../../config'
import { createServer } from '../../server'
import { slash } from '../../../shared/utils'
import {
convertTargets,
cssPlugin,
Expand Down Expand Up @@ -419,6 +421,27 @@ describe('preprocessCSS', () => {
"
`)
})

test('resolves css url() subpath imports from the nearest package.json', async () => {
const root = path.join(dirname, 'fixtures/css-subpath-imports')
const server = await createServer({
configFile: false,
root,
logLevel: 'error',
server: {
middlewareMode: true,
ws: false,
},
})
onTestFinished(() => server.close())

const result = await server.transformRequest('/packages/pkg/src/style.css')
const normalizedCode = slash(result?.code ?? '')

expect(normalizedCode).toMatch(/\/+(packages)\/+(pkg)\/+(src)\/+logo\.png/)
expect(normalizedCode).not.toMatch(/\/+app\/+logo\.png/)
expect(normalizedCode).toContain('#fragment')
})
})

describe('resolveLibCssFilename', () => {
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "app",
"private": true,
"imports": {
"#src/*": "./app/*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "pkg",
"private": true,
"imports": {
"#src/*": "./src/*"
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.logo {
background: url('#src/logo.png');
}
.mask {
mask-image: url('#fragment');
}
59 changes: 52 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type Less from 'less'
import type { RawSourceMap } from '@jridgewell/remapping'
import { WorkerWithFallback } from 'artichokie'
import { globSync } from 'tinyglobby'
import { imports as resolvePackageImports } from 'resolve.exports'
import type {
TransformAttributeResult as LightningCssTransformAttributeResult,
TransformResult as LightningCssTransformResult,
Expand Down Expand Up @@ -83,7 +84,12 @@ import {
urlRE,
} from '../utils'
import type { Logger } from '../logger'
import { cleanUrl, isWindows, slash } from '../../shared/utils'
import {
cleanUrl,
isWindows,
slash,
splitFileAndPostfix,
} from '../../shared/utils'
import { NULL_BYTE_PLACEHOLDER } from '../../shared/constants'
import { createBackCompatIdResolver } from '../idResolver'
import type { ResolveIdFn } from '../idResolver'
Expand All @@ -92,7 +98,7 @@ import type { TransformPluginContext } from '../server/pluginContainer'
import { searchForWorkspaceRoot } from '../server/searchRoot'
import { type DevEnvironment } from '..'
import type { PackageCache } from '../packages'
import { findNearestMainPackageData } from '../packages'
import { findNearestMainPackageData, findNearestPackageData } from '../packages'
import { nodeResolveWithVite } from '../nodeResolve'
import { addToHTMLProxyTransformResult } from './html'
import {
Expand Down Expand Up @@ -305,6 +311,37 @@ export function cssPlugin(config: ResolvedConfig): Plugin {

let preprocessorWorkerController: PreprocessorWorkerController | undefined

const resolveCssSubpathImport = (url: string, importer?: string) => {
if (!importer || !url.startsWith('#')) return

const basedir = path.dirname(importer)
const pkgData = findNearestPackageData(basedir, config.packageCache)
if (!pkgData) return

let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(url.slice(1))
idWithoutPostfix = `#${idWithoutPostfix}`

let importsPath: string | undefined
try {
const conditions = config.resolve.conditions
.filter((condition) => condition !== DEV_PROD_CONDITION)
.concat(config.isProduction ? 'production' : 'development', 'import')
importsPath = resolvePackageImports(pkgData.data, idWithoutPostfix, {
conditions,
unsafe: true,
})?.[0]
} catch {
return
}

if (!importsPath || importsPath[0] !== '.') return

const absolutePath = path.join(pkgData.dir, importsPath)
return fs.existsSync(cleanUrl(absolutePath))
? absolutePath + postfix
: undefined
}

// warm up cache for resolved postcss config
if (config.css.transformer !== 'lightningcss') {
resolvePostcssConfig(config).catch(() => {
Expand Down Expand Up @@ -388,10 +425,15 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
return [joinUrlSegments(base, decodedUrl), undefined]
}
}
const [id, fragment] = decodedUrl.split('#')
let resolved = await resolveUrl(id, importer)
const resolved =
decodedUrl[0] === '#'
? resolveCssSubpathImport(decodedUrl, importer)
: await (async () => {
const { file, postfix } = splitFileAndPostfix(decodedUrl)
const resolved = await resolveUrl(file, importer)
return resolved ? resolved + postfix : undefined
})()
if (resolved) {
if (fragment) resolved += '#' + fragment
let url = await fileToUrl(this, resolved)
// Inherit HMR timestamp if this asset was invalidated
if (!url.startsWith('data:') && this.environment.mode === 'dev') {
Expand All @@ -405,6 +447,10 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
}
return [url, cleanUrl(resolved)]
}
if (decodedUrl[0] === '#') {
// Unresolved leading `#` values are treated as plain URL fragments.
return [url, undefined]
}
if (config.command === 'build') {
const isExternal = config.build.rollupOptions.external
? resolveUserExternal(
Expand Down Expand Up @@ -1362,7 +1408,7 @@ async function compileCSSPreprocessors(
environment.getTopLevelConfig(),
)
const opts = {
...((preprocessorOptions && preprocessorOptions[lang]) || {}),
...(preprocessorOptions && preprocessorOptions[lang]),
// important: set this for relative import resolving
filename: cleanUrl(id),
enableSourcemap: devSourcemap ?? false,
Expand Down Expand Up @@ -2125,7 +2171,6 @@ function skipUrlReplacer(unquotedUrl: string) {
return (
isExternalUrl(unquotedUrl) ||
isDataUrl(unquotedUrl) ||
unquotedUrl[0] === '#' ||
functionCallRE.test(unquotedUrl) ||
// skip if it is already a placeholder
unquotedUrl.startsWith('__VITE_ASSET__') ||
Expand Down
4 changes: 4 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.