Skip to content

Commit

Permalink
fix: Replace asset references in CSS returned to JS
Browse files Browse the repository at this point in the history
  • Loading branch information
Artur- committed Nov 18, 2021
1 parent 04016df commit 74045a5
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 3 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('color:')
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.
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ 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
export const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g

const rawRE = /(\?|&)raw(?:&|$)/
const urlRE = /(\?|&)url(?:&|$)/
Expand Down
13 changes: 11 additions & 2 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ import {
assetUrlRE,
registerAssetToChunk,
fileToUrl,
checkPublicFile
checkPublicFile,
assetUrlQuotedRE
} from './asset'
import MagicString from 'magic-string'
import * as Postcss from 'postcss'
Expand Down Expand Up @@ -242,8 +243,16 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
}
}

// replace asset references before returning the CSS to JS
const finalCss = css.replace(
assetUrlQuotedRE,
(_, fileHash, postfix = '') => {
return config.base + getAssetFilename(fileHash, config) + postfix
}
)

return {
code: css,
code: finalCss,
// TODO CSS source map
map: { mappings: '' }
}
Expand Down

0 comments on commit 74045a5

Please sign in to comment.