Skip to content

Commit

Permalink
fix(vite): repalce css hash in js when generating bundle (#1217)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
nieyuyao and antfu committed Jul 6, 2022
1 parent 026c1f0 commit 0fb167d
Showing 1 changed file with 23 additions and 9 deletions.
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

0 comments on commit 0fb167d

Please sign in to comment.