Skip to content

Commit bb5b18f

Browse files
committed
feat(css): tree shake scoped styles
1 parent 59946d3 commit bb5b18f

File tree

5 files changed

+30
-2
lines changed

5 files changed

+30
-2
lines changed

packages/plugin-vue/src/main.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -275,9 +275,9 @@ export async function transformMain(
275275

276276
return {
277277
code: resolvedCode,
278-
map: resolvedMap || {
278+
map: (resolvedMap || {
279279
mappings: '',
280-
},
280+
}) as any,
281281
meta: {
282282
vite: {
283283
lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || 'js',

packages/plugin-vue/src/style.ts

+7
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,12 @@ export async function transformStyle(
6262
return {
6363
code: result.code,
6464
map: map,
65+
meta: block.scoped
66+
? {
67+
vite: {
68+
cssScopeTo: [descriptor.filename, 'default'],
69+
},
70+
}
71+
: undefined,
6572
}
6673
}

playground/vue/Main.vue

+6
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ import PreCompiledExternalScoped from './pre-compiled/external-scoped.vue'
6666
import PreCompiledExternalCssModules from './pre-compiled/external-cssmodules.vue'
6767
import ParserOptions from './ParserOptions.vue'
6868
import HmrCircularReference from './HmrCircularReference.vue'
69+
import TreeShakeScopedStyle from './TreeShakeScopedStyle.vue'
70+
71+
// NOTE: this function is not used intentionally
72+
function foo() {
73+
console.log(TreeShakeScopedStyle)
74+
}
6975
7076
const TsGeneric = defineAsyncComponent(() => import('./TsGeneric.vue'))
7177
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<template>
2+
<div>tree shake scoped style</div>
3+
</template>
4+
5+
<style scoped>
6+
.tree-shake-scoped-style {
7+
color: red;
8+
}
9+
</style>

playground/vue/__tests__/vue.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { version } from 'vue'
33
import {
44
browserLogs,
55
editFile,
6+
findAssetFile,
67
getBg,
78
getColor,
89
isBuild,
@@ -441,3 +442,8 @@ describe('template parse options', () => {
441442
)
442443
})
443444
})
445+
446+
test.runIf(isBuild)('scoped style should be tree-shakeable', async () => {
447+
const indexCss = findAssetFile(/index-[\w-]+\.css/)
448+
expect(indexCss).not.toContain('.tree-shake-scoped-style')
449+
})

0 commit comments

Comments
 (0)