Skip to content

Commit

Permalink
feat(css): add cssExtract option to build config (vitejs#4345)
Browse files Browse the repository at this point in the history
  • Loading branch information
JackFGreen committed Jan 20, 2022
1 parent 4a764f5 commit 8200b5f
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 27 deletions.
16 changes: 16 additions & 0 deletions packages/playground/css-extract/__tests__/css-extract.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { findAssetFile, getColor, isBuild } from '../../testUtils'

test('should load both stylesheets', async () => {
expect(await getColor('h1')).toBe('red')
expect(await getColor('h2')).toBe('blue')
})

if (isBuild) {
test('should generate correct files', async () => {
expect(findAssetFile(/style.*\.js$/)).toMatch('h2{color')
expect(findAssetFile('main.*.js$')).toMatch('h1{color')

const bothImportStyle = findAssetFile('other.*.js$').replace('\n', '')
expect(findAssetFile('main.*.js$')).toMatch(bothImportStyle)
})
}
2 changes: 2 additions & 0 deletions packages/playground/css-extract/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script type="module" src="/main.js"></script>
<div id="app"></div>
3 changes: 3 additions & 0 deletions packages/playground/css-extract/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h1 {
color: red;
}
6 changes: 6 additions & 0 deletions packages/playground/css-extract/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import './style.css'
import './main.css'

document.getElementById(
'app'
).innerHTML = `<h1>This should be red</h1><h2>This should be blue</h2>`
1 change: 1 addition & 0 deletions packages/playground/css-extract/other.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './style.css'
11 changes: 11 additions & 0 deletions packages/playground/css-extract/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "test-css-css-extract",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"debug": "node --inspect-brk ../../vite/bin/vite",
"preview": "vite preview"
}
}
3 changes: 3 additions & 0 deletions packages/playground/css-extract/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h2 {
color: blue;
}
14 changes: 14 additions & 0 deletions packages/playground/css-extract/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { resolve } = require('path')

module.exports = {
build: {
manifest: true,
cssExtract: false,
rollupOptions: {
input: {
main: resolve(__dirname, './index.html'),
other: resolve(__dirname, './other.js')
}
}
}
}

This file was deleted.

This file was deleted.

8 changes: 8 additions & 0 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ export interface BuildOptions {
* @default 4096
*/
assetsInlineLimit?: number
/**
* Whether to extract CSS. When disabled, CSS will be
* inlined as strings in the chunk, e.g. in lib mode, CSS will be inlined
* in the output file.
* @default true
*/
cssExtract?: boolean
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
Expand Down Expand Up @@ -247,6 +254,7 @@ export function resolveBuildOptions(
outDir: 'dist',
assetsDir: 'assets',
assetsInlineLimit: 4096,
cssExtract: true,
cssCodeSplit: !raw?.lib,
cssTarget: false,
sourcemap: false,
Expand Down
48 changes: 28 additions & 20 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,33 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
return css
}

const inlineCSS2JS = async () => {
// legacy build, inline css
chunkCSS = await processChunkCSS(chunkCSS, {
inlined: true,
minify: true
})
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 }
}
}

if (!config.build.cssExtract) {
return await inlineCSS2JS()
}

if (config.build.cssCodeSplit) {
if (isPureCssChunk) {
// this is a shared CSS-only chunk that is empty.
Expand All @@ -432,26 +459,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
new Set([this.getFileName(fileHandle)])
)
} else if (!config.build.ssr) {
// legacy build, inline css
chunkCSS = await processChunkCSS(chunkCSS, {
inlined: true,
minify: true
})
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 await inlineCSS2JS()
}
} else {
// non-split extracted CSS will be minified together
Expand Down
5 changes: 4 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8200b5f

Please sign in to comment.