Skip to content

Commit c444ab6

Browse files
jkzinghaoqunjiang
authored andcommitted
fix: avoid to generate empty css chunk files (#1464)
* test: add failing test * fix: filter out empty styles before generating code * feat: improve regex
1 parent 9337655 commit c444ab6

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed

lib/codegen/styleInjection.js

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const { attrsToQuery } = require('./utils')
22
const hotReloadAPIPath = JSON.stringify(require.resolve('vue-hot-reload-api'))
3+
const nonWhitespaceRE = /\S+/
34

45
module.exports = function genStyleInjectionCode (
56
loaderContext,
@@ -69,6 +70,8 @@ module.exports = function genStyleInjectionCode (
6970
}
7071
}
7172

73+
// filter out empty styles (with no `src` specified or only contains whitespaces)
74+
styles = styles.filter(style => style.src || nonWhitespaceRE.test(style.content))
7275
// explicit injection is needed in SSR (for critical CSS collection)
7376
// or in Shadow Mode (for injection into shadow root)
7477
// In these modes, vue-style-loader exports objects with the __inject__

test/advanced.spec.js

+32
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,38 @@ test('extract CSS', done => {
137137
})
138138
})
139139

140+
test('extract CSS with code spliting', done => {
141+
bundle({
142+
entry: 'extract-css-chunks.vue',
143+
modify: config => {
144+
config.module.rules = [
145+
{
146+
test: /\.vue$/,
147+
use: 'vue-loader'
148+
},
149+
{
150+
test: /\.css$/,
151+
use: [
152+
MiniCssExtractPlugin.loader,
153+
'css-loader'
154+
]
155+
}
156+
]
157+
},
158+
plugins: [
159+
new MiniCssExtractPlugin({
160+
filename: 'test.output.css'
161+
})
162+
]
163+
}, code => {
164+
const css = normalizeNewline(mfs.readFileSync('/test.output.css').toString())
165+
expect(css).toContain(`h1 {\n color: red;\n}`)
166+
expect(mfs.existsSync('/empty.test.output.css')).toBe(false)
167+
expect(mfs.existsSync('/basic.test.output.css')).toBe(true)
168+
done()
169+
})
170+
})
171+
140172
test('support rules with oneOf', async () => {
141173
const run = (entry, assert) => new Promise((resolve, reject) => {
142174
mockBundleAndRun({

test/fixtures/empty-style.vue

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<template>
2+
<h1>empty style</h1>
3+
</template>
4+
5+
<style>
6+
</style>

test/fixtures/extract-css-chunks.vue

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<template>
2+
<div>
3+
<basic></basic>
4+
<empty-style></empty-style>
5+
</div>
6+
</template>
7+
8+
<script>
9+
export default {
10+
components: {
11+
Basic: () => import(/* webpackChunkName: "basic" */ './basic.vue'),
12+
EmptyStyle: () => import(/* webpackChunkName: "empty" */ './empty-style.vue')
13+
}
14+
}
15+
</script>
16+
17+
<style>
18+
h1 {
19+
color: red;
20+
}
21+
</style>

0 commit comments

Comments
 (0)