Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: scope css to js module to allow treeshaking it (requires vite 6.2) #1092

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/plenty-eyes-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

scope css to js module to enable treeshaking scoped css from unused components. Requires vite 6.2
37 changes: 37 additions & 0 deletions packages/e2e-tests/css-treeshake/__tests__/css-treeshake.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { browserLogs, findAssetFile, getColor, getEl, getText, isBuild } from '~utils';
import { expect } from 'vitest';

test('should not have failed requests', async () => {
browserLogs.forEach((msg) => {
expect(msg).not.toMatch('404');
});
});

test('should apply css from used components', async () => {
expect(await getText('#app')).toBe('App');
expect(await getColor('#app')).toBe('blue');
expect(await getText('#a')).toBe('A');
expect(await getColor('#a')).toBe('red');
});

test('should apply css from unused components that contain global styles', async () => {
expect(await getEl('head style[src]'));
expect(await getColor('#test')).toBe('green'); // from B.svelte
});

test('should not render unused components', async () => {
expect(await getEl('#b')).toBeNull();
expect(await getEl('#c')).toBeNull();
});

if (isBuild) {
test('should include unscoped global styles from unused components', async () => {
const cssOutput = findAssetFile(/index-.*\.css/);
expect(cssOutput).toContain('#test{color:green}'); // from B.svelte
});
test('should not include scoped styles from unused components', async () => {
const cssOutput = findAssetFile(/index-.*\.css/);
// from C.svelte
expect(cssOutput).not.toContain('.unused');
});
}
13 changes: 13 additions & 0 deletions packages/e2e-tests/css-treeshake/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />

<title>Svelte app</title>

<script type="module" src="/src/main.js"></script>
</head>

<body></body>
</html>
17 changes: 17 additions & 0 deletions packages/e2e-tests/css-treeshake/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "e2e-tests-css-treeshake",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "workspace:^",
"sass": "^1.85.1",
"svelte": "^5.20.5",
"vite": "^6.2.0"
}
}
7 changes: 7 additions & 0 deletions packages/e2e-tests/css-treeshake/src/A.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<h1 id="a">A</h1>

<style>
h1 {
color: red;
}
</style>
13 changes: 13 additions & 0 deletions packages/e2e-tests/css-treeshake/src/App.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
import { A } from './barrel.js';
</script>

<div id="test">test</div>
<h1 id="app">App</h1>
<A />

<style>
#app {
color: blue;
}
</style>
10 changes: 10 additions & 0 deletions packages/e2e-tests/css-treeshake/src/B.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<h1 id="b">B</h1>

<style>
h1 {
color: green;
}
:global(#test) {
color: green;
}
</style>
14 changes: 14 additions & 0 deletions packages/e2e-tests/css-treeshake/src/C.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<h1 id="c" class="unused"><strong>C</strong></h1>

<style>
.unused {
color: magenta;
}
h1 :global {
background: blue;
}

h1 :global(strong) {
color: magenta;
}
</style>
4 changes: 4 additions & 0 deletions packages/e2e-tests/css-treeshake/src/barrel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { default as A } from './A.svelte';
// B and C are unused, their css should not be included
export { default as B } from './B.svelte';
export { default as C } from './C.svelte';
3 changes: 3 additions & 0 deletions packages/e2e-tests/css-treeshake/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import App from './App.svelte';
import { mount } from 'svelte';
mount(App, { target: document.body });
2 changes: 2 additions & 0 deletions packages/e2e-tests/css-treeshake/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />
5 changes: 5 additions & 0 deletions packages/e2e-tests/css-treeshake/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

export default {
preprocess: [vitePreprocess()]
};
7 changes: 7 additions & 0 deletions packages/e2e-tests/css-treeshake/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { env } from 'node:process';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()]
});
15 changes: 13 additions & 2 deletions packages/vite-plugin-svelte/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,20 @@ export function svelte(inlineOptions) {
};
} else {
if (query.svelte && query.type === 'style') {
const css = cache.getCSS(svelteRequest);
// @ts-expect-error __meta does not exist
const { __meta, ...css } = cache.getCSS(svelteRequest);
if (css) {
return css;
if (__meta?.hasUnscopedGlobalCss) {
return css; // css contains unscoped global, do not scope to component
}
return {
...css,
meta: {
vite: {
cssScopeTo: [svelteRequest.filename, 'default']
}
}
};
}
}
// prevent vite asset plugin from loading files as url that should be compiled in transform
Expand Down
3 changes: 3 additions & 0 deletions packages/vite-plugin-svelte/src/types/compile.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export interface Code {
code: string;
map?: any;
dependencies?: any[];
__meta?: {
hasUnscopedGlobalCss?: boolean;
};
}

export interface CompileData {
Expand Down
41 changes: 31 additions & 10 deletions packages/vite-plugin-svelte/src/utils/compile.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as svelte from 'svelte/compiler';

import { safeBase64Hash } from './hash.js';
import { log } from './log.js';

Expand Down Expand Up @@ -69,18 +68,30 @@ export function createCompileSvelte() {
}

let preprocessed;
let preprocessors = options.preprocess;
let hasUnscopedGlobalCss = false;
const preprocessors = options.preprocess
? Array.isArray(options.preprocess)
? [...options.preprocess]
: [options.preprocess]
: [];

if (!options.isBuild && options.emitCss && compileOptions.hmr) {
// inject preprocessor that ensures css hmr works better
if (!Array.isArray(preprocessors)) {
preprocessors = preprocessors
? [preprocessors, devStylePreprocessor]
: [devStylePreprocessor];
} else {
preprocessors = preprocessors.concat(devStylePreprocessor);
}
preprocessors.push(devStylePreprocessor);
}
if (preprocessors) {

if (options.emitCss) {
// check if css has unscoped global rules
// This is later used to decide if css output can be scoped to the js module for treeshaking
preprocessors.push({
name: 'test-has-global-style',
style({ content }) {
hasUnscopedGlobalCss = /(?:^|,)\s*(?::global[\s{(]|@keyframes -global-)/m.test(content);
}
});
}

if (preprocessors.length > 0) {
try {
preprocessed = await svelte.preprocess(code, preprocessors, { filename }); // full filename here so postcss works
} catch (e) {
Expand Down Expand Up @@ -133,6 +144,16 @@ export function createCompileSvelte() {
let compiled;
try {
compiled = svelte.compile(finalCode, { ...finalCompileOptions, filename });

if (compiled.css && hasUnscopedGlobalCss) {
Object.defineProperty(compiled.css, '__meta', {
value: { hasUnscopedGlobalCss },
writable: false,
enumerable: false,
configurable: false
});
}

// patch output with partial accept until svelte does it
// TODO remove later
if (
Expand Down
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

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