Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(build): import node:fs statically so Vite plugin package discovery survives the ESM build (#4972)

Ishan Jainfb2d385e37e2
diff --git a/.changeset/build-vite-esm-fs-require.md b/.changeset/build-vite-esm-fs-require.md
new file mode 100644
index 0000000000..c975666dc7
--- /dev/null
+++ b/.changeset/build-vite-esm-fs-require.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/build': patch
+---
+
+[fix] build: import `node:fs` statically so the Vite plugin's package discovery survives the ESM build
+
+`astryxStylex()`'s config plugin discovered installed `@astryxdesign/*` packages with `require('node:fs')`. The `./vite` export ships only an ESM bundle (`dist/vite.mjs`, esbuild `format: 'esm'`), where esbuild lowers `require` to a shim that throws `Dynamic require of "node:fs" is not supported` — always, since native `require` never exists under ESM. The surrounding `try/catch` swallowed the throw, so `optimizeDeps.exclude` silently fell back to `['@astryxdesign/core']` and every other installed Astryx package stayed eligible for Vite pre-bundling, which strips `stylex.create`/`defineVars` calls and causes runtime errors.
+
+The discovery now uses a static `import fs from 'node:fs'`, which esbuild preserves as a real ESM import. A regression test compiles `vite.ts` with the same esbuild options as `build.mjs` and runs the discovery in a child `node` process, since in-process test runners provide a `require` shim that masks the bug.
+
+@is-jain
diff --git a/packages/build/build.mjs b/packages/build/build.mjs
index 51457c4263..a37d3b4769 100644
--- a/packages/build/build.mjs
+++ b/packages/build/build.mjs
@@ -18,12 +18,14 @@ buildSync({
platform: 'node',
format: 'esm',
outfile: 'dist/vite.mjs',
+ // SYNC: keep aligned with the external list in src/vite.test.ts
external: [
'vite',
'@stylexjs/babel-plugin',
'@stylexjs/unplugin',
'path',
'url',
+ 'node:fs',
'node:path',
'node:url',
],
diff --git a/packages/build/src/vite.test.ts b/packages/build/src/vite.test.ts
index b2df91b9cf..3937645700 100644
--- a/packages/build/src/vite.test.ts
+++ b/packages/build/src/vite.test.ts
@@ -7,13 +7,22 @@
* theme layer name is fixed at `astryx-theme`.
*/
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, beforeAll, afterAll} from 'vitest';
+import {mkdtempSync, mkdirSync, rmSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
import {astryxStylex} from './vite';
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
/** Pull the injected `@layer ...;` order statement out of the plugin set. */
function getLayerOrder(plugins: ReturnType<typeof astryxStylex>): string {
const layerPlugin = plugins.find(p => p.name === 'astryx-css-layer-order');
- expect(layerPlugin, 'astryx-css-layer-order plugin should exist').toBeTruthy();
+ expect(
+ layerPlugin,
+ 'astryx-css-layer-order plugin should exist',
+ ).toBeTruthy();
const transform = (layerPlugin as any).transformIndexHtml;
const tags =
typeof transform === 'function' ? transform() : transform.handler();
@@ -43,3 +52,98 @@ describe('astryxStylex layer order (legacy API)', () => {
expect(order).toBe('@layer reset, astryx-base, astryx-theme, product;');
});
});
+
+describe('astryxStylex optimizeDeps package discovery', () => {
+ let rootDir: string;
+
+ beforeAll(() => {
+ rootDir = mkdtempSync(path.join(tmpdir(), 'astryx-vite-'));
+ for (const pkg of ['core', 'icons', 'charts']) {
+ mkdirSync(path.join(rootDir, 'node_modules', '@astryxdesign', pkg), {
+ recursive: true,
+ });
+ }
+ mkdirSync(path.join(rootDir, 'node_modules', '@astryxdesign', '.cache'), {
+ recursive: true,
+ });
+ });
+
+ afterAll(() => {
+ rmSync(rootDir, {recursive: true, force: true});
+ });
+
+ function getExclude(rootDirOption: string): string[] {
+ const plugins = astryxStylex({rootDir: rootDirOption});
+ const configPlugin = plugins.find(p => p.name === 'astryx-config');
+ expect(configPlugin, 'astryx-config plugin should exist').toBeTruthy();
+ const config = (configPlugin as any).config;
+ const result = typeof config === 'function' ? config() : config.handler();
+ return result.optimizeDeps.exclude;
+ }
+
+ it('excludes every installed @astryxdesign/* package, not just core', () => {
+ expect(getExclude(rootDir).sort()).toEqual([
+ '@astryxdesign/charts',
+ '@astryxdesign/core',
+ '@astryxdesign/icons',
+ ]);
+ });
+
+ it('falls back to @astryxdesign/core when no packages are installed', () => {
+ expect(getExclude(path.join(rootDir, 'does-not-exist'))).toEqual([
+ '@astryxdesign/core',
+ ]);
+ });
+
+ // Vitest's module transform provides a working `require` even for dynamic
+ // file-URL imports, so an in-process test cannot catch CJS-isms that only
+ // break in the shipped ESM bundle. This test compiles vite.ts exactly like
+ // build.mjs does, then runs the discovery in a child `node` process under
+ // real ESM semantics (where `require` is undefined).
+ it('still discovers packages in the compiled ESM bundle (dist contract)', async () => {
+ const {buildSync} = await import('esbuild');
+ const {execFileSync} = await import('node:child_process');
+ // Emit next to src/ so the bundle's externals (vite, @stylexjs/*)
+ // resolve against this package's node_modules; dist/ is gitignored.
+ const outfile = path.join(__dirname, '..', 'dist', 'vite.test-esm.mjs');
+ try {
+ buildSync({
+ entryPoints: [path.join(__dirname, 'vite.ts')],
+ bundle: true,
+ platform: 'node',
+ format: 'esm',
+ outfile,
+ // SYNC: keep aligned with the external list in build.mjs
+ external: [
+ 'vite',
+ '@stylexjs/babel-plugin',
+ '@stylexjs/unplugin',
+ 'path',
+ 'url',
+ 'node:fs',
+ 'node:path',
+ 'node:url',
+ ],
+ });
+ const script = [
+ `const {astryxStylex} = await import(${JSON.stringify(pathToFileURL(outfile).href)});`,
+ `const plugin = astryxStylex({rootDir: ${JSON.stringify(rootDir)}})`,
+ ` .find(p => p.name === 'astryx-config');`,
+ `console.log(JSON.stringify(plugin.config().optimizeDeps.exclude));`,
+ ].join('\n');
+ const stdout = execFileSync(
+ process.execPath,
+ ['--input-type=module', '-e', script],
+ {encoding: 'utf8'},
+ );
+ const exclude: string[] = JSON.parse(stdout.trim());
+ expect(exclude.sort()).toEqual([
+ '@astryxdesign/charts',
+ '@astryxdesign/core',
+ '@astryxdesign/icons',
+ ]);
+ } finally {
+ rmSync(outfile, {force: true});
+ }
+ });
+});
diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts
index 234e998f9f..d5633d1253 100644
--- a/packages/build/src/vite.ts
+++ b/packages/build/src/vite.ts
@@ -3,6 +3,7 @@
import type {Plugin, UserConfig} from 'vite';
import stylexBabelPlugin from '@stylexjs/babel-plugin';
import stylex from '@stylexjs/unplugin';
+import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
@@ -189,13 +190,12 @@ export function astryxStylex(
// strips stylex.create/defineVars calls and causes runtime errors.
let xdsPackages: string[] = ['@astryxdesign/core'];
try {
- const fs = require('node:fs');
const xdsDir = path.resolve(rootDir, 'node_modules/@astryxdesign');
if (fs.existsSync(xdsDir)) {
xdsPackages = fs
.readdirSync(xdsDir)
- .filter((name: string) => !name.startsWith('.'))
- .map((name: string) => `@astryxdesign/${name}`);
+ .filter(name => !name.startsWith('.'))
+ .map(name => `@astryxdesign/${name}`);
}
} catch {
// Fallback to just @astryxdesign/core if discovery fails