Skip to content
Closed
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/vite-plugin-extract-option.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vanilla-extract/vite-plugin': minor
---

Add an `extract` option to the Vite plugin, mirroring the Rollup plugin. CSS can be emitted as per-file assets (`extract: false`) or combined into a single plugin-emitted CSS bundle with side-effect imports stripped (`extract: { name, sourcemap }`). The default (`undefined`) keeps Vite's native CSS pipeline untouched.
3 changes: 2 additions & 1 deletion packages/vite-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"license": "MIT",
"dependencies": {
"@vanilla-extract/compiler": "workspace:^",
"@vanilla-extract/integration": "workspace:^"
"@vanilla-extract/integration": "workspace:^",
"magic-string": "^0.30.17"
},
"devDependencies": {
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
Expand Down
166 changes: 166 additions & 0 deletions packages/vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
ModuleNode,
ViteDevServer,
} from 'vite';
import { posix } from 'path';
import { type Compiler, createCompiler } from '@vanilla-extract/compiler';
import {
cssFileFilter,
Expand All @@ -17,6 +18,7 @@ import {
normalizePath,
} from '@vanilla-extract/integration';
import { getAbsoluteId } from './ids';
import { generateCssBundle, stripSideEffectImportsMatching } from './lib';

const PLUGIN_NAMESPACE = 'vite-plugin-vanilla-extract';
const virtualExtCss = '.vanilla.css';
Expand All @@ -43,6 +45,37 @@ interface Options {
identifiers?: IdentifierOption;
unstable_pluginFilter?: PluginFilter;
unstable_mode?: 'transform' | 'emitCss' | 'inlineCssInDev';
/**
* Controls how compiled CSS is emitted when building, mirroring the `extract`
* option of the Rollup plugin.
*
* - `undefined` (default): CSS is handled by Vite's native CSS pipeline,
* e.g. bundled into a single `.css` file per entry in library mode.
* - `false`: Each `.css.ts` file is emitted as its own CSS asset (e.g.
* `assets/button.css.ts.vanilla.css`) and JS files keep side-effect
* imports of those assets.
* - `{ name?, sourcemap? }`: All CSS is combined into a single asset emitted
* by the plugin, and side-effect CSS imports are stripped from JS output.
*
* Only applies when building, and has no effect when
* `unstable_mode: 'transform'` is set.
*
* @default undefined
*/
extract?:
| {
/**
* Name of emitted .css file.
* @default "bundle.css"
*/
name?: string;
/**
* Generate a .css.map file?
* @default false
*/
sourcemap?: boolean;
}
| false;
}

// Plugins that we know are compatible with the `vite-node` compiler
Expand All @@ -61,6 +94,7 @@ export function vanillaExtractPlugin({
identifiers,
unstable_pluginFilter: pluginFilter = defaultPluginFilter,
unstable_mode = 'emitCss',
extract,
}: Options = {}): Plugin[] {
let config: ResolvedConfig;
let configEnv: ConfigEnv;
Expand All @@ -73,6 +107,16 @@ export function vanillaExtractPlugin({

const transformedModules = new Set<string>();

// Only used when `extract: { ... }` is configured
let extractedCssIds = new Set<string>();
// Only used when `extract: false` is configured; module id -> asset id
const emittedCssAssets = new Map<string, string>();

const extractApplies = () =>
config.command === 'build' &&
extract !== undefined &&
unstable_mode !== 'transform';

const getIdentOption = () =>
identifiers ?? (config.mode === 'production' ? 'short' : 'debug');

Expand Down Expand Up @@ -262,16 +306,127 @@ export function vanillaExtractPlugin({
packageName = getPackageInfo(config.root).name;
},
async buildStart() {
// Reset extract state between builds, e.g. in watch mode
extractedCssIds = new Set();
emittedCssAssets.clear();

// Ensure we re-use the compiler instance between builds, e.g. in watch mode
await ensureCompiler();
},
buildEnd() {
// Generate CSS bundle (if extracting)
if (extract && extractApplies()) {
// Note: this can't happen earlier than buildEnd because the module
// graph isn't complete until this point
const { bundle, extractedCssIds: extractedIds } =
generateCssBundle(this);
extractedCssIds = extractedIds;

const name = extract.name || 'bundle.css';
this.emitFile({
type: 'asset',
name,
originalFileName: name,
source: bundle.toString(),
});

if (extract.sourcemap) {
const sourcemapName = `${name}.map`;
this.emitFile({
type: 'asset',
name: sourcemapName,
originalFileName: sourcemapName,
source: bundle
.generateMap({ file: name, includeContent: true })
.toString(),
});
}
}

// When using the rollup watcher, we don't want to close the compiler after every build.
// Instead, we close it when the watcher is closed via the closeWatcher hook.
if (!config.build.watch) {
compiler?.close();
}
},
// Emit per-file CSS assets and replace CSS import paths with relative
// paths to the emitted files (only for `extract: false`)
renderChunk(code, chunkInfo) {
if (extract !== false || !extractApplies()) {
return null;
}

const chunkPath = posix.dirname(chunkInfo.fileName);
let output = code;

// Process longest specifiers first so a specifier that is a substring
// of another (e.g. nested paths sharing a suffix) can't be corrupted
// by an earlier replacement
const cssImportPaths = [...chunkInfo.imports].sort(
(pathA, pathB) => pathB.length - pathA.length,
);

for (const importPath of cssImportPaths) {
const moduleInfo = this.getModuleInfo(importPath);

if (!moduleInfo) {
continue;
}

const css = moduleInfo.meta.css;

if (typeof css !== 'string') {
continue;
}

let assetId = emittedCssAssets.get(importPath);

if (!assetId) {
assetId = this.emitFile({
type: 'asset',
name: posix.basename(moduleInfo.id),
originalFileName: moduleInfo.id,
source: css,
});
emittedCssAssets.set(importPath, assetId);
}

const assetPath = this.getFileName(assetId);
const relativeAssetPath = `./${posix.normalize(
posix.relative(chunkPath, assetPath),
)}`;

output = output.replace(importPath, relativeAssetPath);
}

if (output === code) {
return null;
}

return {
code: output,
map: null,
};
},
// Remove side effect CSS imports (only for `extract: { ... }`)
generateBundle(_options, bundle) {
if (!extract || !extractApplies()) {
return;
}

for (const chunk of Object.values(bundle)) {
const isJsFile = /\.(m|c)?js$/.test(chunk.fileName);
if (
chunk.type === 'chunk' &&
isJsFile &&
chunk.imports.some((specifier) => extractedCssIds.has(specifier))
) {
chunk.code = stripSideEffectImportsMatching(chunk.code, [
...extractedCssIds,
]);
}
}
},
closeWatcher() {
return compiler?.close();
},
Expand Down Expand Up @@ -377,6 +532,17 @@ export function vanillaExtractPlugin({
const css = await ensureCssForVirtualId(absoluteId);

if (css) {
if (extractApplies()) {
// Hand CSS emission over to the plugin's extract machinery. The
// virtual CSS module is marked external so Vite's CSS pipeline
// never bundles it; renderChunk/buildEnd/generateBundle take over.
return {
id: absoluteId,
external: true,
meta: { css },
};
}

// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
}
Expand Down
154 changes: 154 additions & 0 deletions packages/vite-plugin/src/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { cssFileFilter } from '@vanilla-extract/integration';
import MagicString, { Bundle as MagicStringBundle } from 'magic-string';

/**
* Machinery for the `extract` option, ported from
* `@vanilla-extract/rollup-plugin/src/lib.ts` so the Vite plugin stays
* self-contained. behavioural changes here should generally be mirrored
* there.
*
* Deliberate divergences: the side-effect import regex below must also match
* Vite's minified single-line output, and the compiled CSS is narrowed with
* `typeof css === 'string'` rather than a truthy check to satisfy Vite 8's
* (rolldown) module meta typing.
*/

/**
* Minimal structural types for the parts of the bundler plugin context used
* below, so this module doesn't need to depend on bundler types directly.
*/
interface VanillaModuleInfo {
id: string;
isEntry: boolean;
/** The ids of the modules importing this module */
importers: readonly string[];
/** The ids of the modules imported by this module, in import order */
importedIds: readonly string[];
/** Custom plugin options, e.g. `meta.css` for extracted CSS */
meta: Record<string, unknown>;
}

interface CssBundlePluginContext {
getModuleIds: () => Iterable<string>;
getModuleInfo: (id: string) => VanillaModuleInfo | null;
warn: (warning: string) => void;
}

/** Generate a CSS bundle from a Rollup context */
export function generateCssBundle(plugin: CssBundlePluginContext): {
bundle: MagicStringBundle;
extractedCssIds: Set<string>;
} {
const cssBundle = new MagicStringBundle();
const extractedCssIds = new Set<string>();

// 1. identify CSS files to bundle
const cssFiles: Record<string, ImportChain> = {};
for (const id of plugin.getModuleIds()) {
if (cssFileFilter.test(id)) {
cssFiles[id] = buildImportChain(id, plugin);
}
}

// 2. build bundle from import order
for (const id of sortModules(cssFiles)) {
const { importedIds } = plugin.getModuleInfo(id) ?? {};
for (const importedId of importedIds ?? []) {
const resolution = plugin.getModuleInfo(importedId);
const css = resolution?.meta.css;

if (
resolution &&
typeof css === 'string' &&
!extractedCssIds.has(resolution.id)
) {
extractedCssIds.add(resolution.id);
cssBundle.addSource({
filename: resolution.id,
content: new MagicString(css),
});
}
}
}

return { bundle: cssBundle, extractedCssIds };
}

/** [id, order] tuple meant for ordering imports */
export type ImportChain = [id: string, order: number][];

/** Trace a file back through its importers, building an ordered list */
export function buildImportChain(
id: string,
plugin: Pick<CssBundlePluginContext, 'getModuleInfo' | 'warn'>,
): ImportChain {
let mod: VanillaModuleInfo | null = plugin.getModuleInfo(id);
if (!mod) {
return [];
}
/** [id, order] */
const chain: ImportChain = [[id, -1]];
// resolve upwards to root entry
while (!mod.isEntry) {
const { id: currentId, importers } = mod;
const lastImporterId = importers.at(-1);
if (!lastImporterId) {
break;
}
if (chain.some(([id]) => id === lastImporterId)) {
plugin.warn(
`Circular import detected. Can’t determine ideal import order of module.\n${chain
.reverse()
.join('\n → ')}`,
);
break;
}
mod = plugin.getModuleInfo(lastImporterId);
if (!mod) {
break;
}
// importedIds preserves the import order within each module
chain.push([lastImporterId, mod.importedIds.indexOf(currentId)]);
}
return chain.reverse();
}

/** Compare import chains to determine a flat ordering for modules */
export function sortModules(modules: Record<string, ImportChain>): string[] {
const sortedModules = Object.entries(modules);

sortedModules.sort(([_idA, chainA], [_idB, chainB]) => {
const shorterChain = Math.min(chainA.length, chainB.length);
for (let i = 0; i < shorterChain; i++) {
const [moduleA, orderA] = chainA[i];
const [moduleB, orderB] = chainB[i];
// on same node, continue to next one
if (moduleA === moduleB && orderA === orderB) {
continue;
}
if (orderA !== orderB) {
return orderA - orderB;
}
}
return 0;
});

return sortedModules.map(([id]) => id);
}

// Matches side-effect `import '...'` / `require('...')` statements. Unlike the
// equivalent helper in the Rollup plugin, this is not anchored to the start of
// a line and allows no whitespace after `import`, so it also matches the
// minified single-line output Vite emits by default. The lookbehind ensures
// the keyword isn't part of a longer identifier (e.g. `foo.import`).
const SIDE_EFFECT_IMPORT_RE =
/(?<![\w.$])(?:import\s*['"]([^'"]+)['"]\s*;?|require\s*\(\s*['"]([^'"]+)['"]\s*\)\s*;?)[ \t]*(?:\r?\n)?/g;

/** Remove specific side effect imports and requires from JS */
export const stripSideEffectImportsMatching = (
code: string,
sources: string[],
): string =>
code.replace(SIDE_EFFECT_IMPORT_RE, (match, importSource, requireSource) =>
sources.includes(importSource ?? requireSource) ? '' : match,
);
Loading