Skip to content

Commit

Permalink
fix: inline async css for legacy builds
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jan 20, 2021
1 parent c821f09 commit 940d483
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { CLIENT_PUBLIC_PATH } from '../constants'
import { ProcessOptions, Result, Plugin as PostcssPlugin } from 'postcss'
import { ViteDevServer } from '../'
import { assetUrlRE, urlToBuiltUrl } from './asset'
import MagicString from 'magic-string'

// const debug = createDebugger('vite:css')

Expand Down Expand Up @@ -221,13 +222,32 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
if (config.build.minify) {
chunkCSS = await minifyCSS(chunkCSS, config)
}
// emit corresponding css file
const fileHandle = this.emitFile({
name: chunk.name + '.css',
type: 'asset',
source: chunkCSS
})
chunkToEmittedCssFileMap.set(chunk, fileHandle)
if (opts.format === 'es') {
// emit corresponding css file
const fileHandle = this.emitFile({
name: chunk.name + '.css',
type: 'asset',
source: chunkCSS
})
chunkToEmittedCssFileMap.set(chunk, fileHandle)
} else {
// legacy build, inline css
const style = `__vite_style__`
const injectCode =
`var ${style} = document.createElement('style');` +
`${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
`document.head.appendChild(${style});`
if (config.build.sourcemap) {
const s = new MagicString(code)
s.prepend(injectCode)
return {
code: s.toString(),
map: s.generateMap({ hires: true })
}
} else {
return { code: injectCode + code }
}
}
return {
code,
map: null
Expand Down

0 comments on commit 940d483

Please sign in to comment.