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(vite): repalce css hash in js when generating bundle #1217

Merged
merged 2 commits into from Jul 6, 2022
Merged
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
32 changes: 23 additions & 9 deletions packages/vite/src/modes/global/build.ts
Expand Up @@ -146,11 +146,11 @@ export function GlobalModeBuildPlugin({ uno, ready, extract, tokens, filter, get
enforce: 'post',
// rewrite the css placeholders
async generateBundle(options, bundle) {
const files = Object.keys(bundle)
const cssFiles = files
.filter(i => i.endsWith('.css'))
const files = Object.entries(bundle)
const cssFiles = files.filter(i => i[0].endsWith('.css'))
const jsFiles = files.filter(i => i[0].endsWith('.js'))

if (!cssFiles.length)
if (!cssFiles.length && !jsFiles.length)
return

if (!vfsLayers.size) {
Expand All @@ -162,17 +162,31 @@ export function GlobalModeBuildPlugin({ uno, ready, extract, tokens, filter, get
const result = await generateAll()
let replaced = false

for (const file of cssFiles) {
const chunk = bundle[file]
for (const [, chunk] of cssFiles) {
if (chunk.type === 'asset' && typeof chunk.source === 'string') {
const css = chunk.source
.replace(HASH_PLACEHOLDER_RE, '')

chunk.source = await replaceAsync(css, LAYER_PLACEHOLDER_RE, async (_, __, layer) => {
replaced = true
return await applyCssTransform(layer === LAYER_MARK_ALL
const css = layer === LAYER_MARK_ALL
? result.getLayers(undefined, Array.from(vfsLayers))
: result.getLayer(layer) || ''
return await applyCssTransform(css, `${chunk.fileName}.css`, options.dir)
})
}
}

// replace the hash in the js files (iife or umd bundle)
for (const [, chunk] of jsFiles) {
if (chunk.type === 'chunk' && typeof chunk.code === 'string') {
const js = chunk.code
.replace(HASH_PLACEHOLDER_RE, '')
chunk.code = await replaceAsync(js, LAYER_PLACEHOLDER_RE, async (_, __, layer) => {
replaced = true
const css = layer === LAYER_MARK_ALL
? result.getLayers(undefined, Array.from(vfsLayers))
: result.getLayer(layer) || '', `${chunk.fileName}.css`, options.dir)
: result.getLayer(layer) || ''
return css
})
}
}
Expand Down