Skip to content

Commit

Permalink
fix: replace asset references in CSS returned to JS (#5729)
Browse files Browse the repository at this point in the history
  • Loading branch information
Artur- authored Nov 22, 2021
1 parent eee9406 commit 880026e
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
7 changes: 7 additions & 0 deletions packages/playground/css/__tests__/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,13 @@ test('inlined', async () => {
expect(await getColor('.inlined')).toBe('black')
})

test('inlined-code', async () => {
const code = await page.textContent('.inlined-code')
// should resolve assets
expect(code).toContain('background:')
expect(code).not.toContain('__VITE_ASSET__')
})

test('minify css', async () => {
if (!isBuild) {
return
Expand Down
1 change: 1 addition & 0 deletions packages/playground/css/inlined.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.inlined {
color: green;
background: url('./ok.png');
}
Binary file added packages/playground/css/ok.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 12 additions & 6 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ import { normalizePath } from '../utils'

export const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g

// urls in JS must be quoted as strings, so when replacing them we need
// a different regex
const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g

const rawRE = /(\?|&)raw(?:&|$)/
const urlRE = /(\?|&)url(?:&|$)/

Expand Down Expand Up @@ -85,7 +81,16 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
renderChunk(code, chunk) {
let match: RegExpExecArray | null
let s: MagicString | undefined
while ((match = assetUrlQuotedRE.exec(code))) {

// Urls added with JS using e.g.
// imgElement.src = "my/file.png" are using quotes

// Urls added in CSS that is imported in JS end up like
// var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";

// In both cases, the wrapping should already be fine

while ((match = assetUrlRE.exec(code))) {
s = s || (s = new MagicString(code))
const [full, hash, postfix = ''] = match
// some internal plugins may still need to emit chunks (e.g. worker) so
Expand All @@ -96,9 +101,10 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
match.index,
match.index + full.length,
JSON.stringify(outputFilepath)
outputFilepath
)
}

if (s) {
return {
code: s.toString(),
Expand Down

0 comments on commit 880026e

Please sign in to comment.