From 7f7212a177e4b1e999467b9ddc97e0032c46a60b Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 10:55:50 +0900 Subject: [PATCH] fix(plugins): watch the configs devup.json extends in webpack and Rsbuild Vite collects every file loadDevupConfig reads through extends and watches them. webpack watched only a devup.json that existed when apply ran, and Rsbuild did not reload devup.json in dev at all, so editing a base theme, or adding or deleting devup.json, left the old CSS, types and default theme in place (PLG-08). Both now pass an inputs set to loadDevupConfig and keep the files it names. webpack stamps them in watchRun and adds them to each compilation's file dependencies, or its missing dependencies while one does not exist; Rsbuild stamps them in watchRun and adds them to each transformed module's dependencies, or missing dependencies. A changed, added or deleted config reloads the theme. Refs #686 Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_config_extends_watch.json | 9 ++ .../src/__tests__/atom-hoist.test.ts | 2 +- .../src/__tests__/checkout-isolation.test.ts | 2 + .../src/__tests__/plugin.test.ts | 83 +++++++++++++++++ packages/rsbuild-plugin/src/plugin.ts | 26 ++++-- .../src/__tests__/plugin.test.ts | 92 +++++++++++++++---- packages/webpack-plugin/src/plugin.ts | 45 +++++---- 7 files changed, 208 insertions(+), 51 deletions(-) create mode 100644 .changepacks/changepack_log_config_extends_watch.json diff --git a/.changepacks/changepack_log_config_extends_watch.json b/.changepacks/changepack_log_config_extends_watch.json new file mode 100644 index 000000000..19bee8293 --- /dev/null +++ b/.changepacks/changepack_log_config_extends_watch.json @@ -0,0 +1,9 @@ +{ + "changes": { + "packages/webpack-plugin/package.json": "Patch", + "packages/rsbuild-plugin/package.json": "Patch", + "packages/next-plugin/package.json": "Patch" + }, + "note": "webpack (and Next.js on webpack) and Rsbuild watch every config `devup.json` extends, as Vite does, and reload the theme when one is edited, added or deleted. Rsbuild did not reload `devup.json` itself in dev before; webpack only watched a `devup.json` that existed when the build started", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/packages/rsbuild-plugin/src/__tests__/atom-hoist.test.ts b/packages/rsbuild-plugin/src/__tests__/atom-hoist.test.ts index a11716515..e46b08139 100644 --- a/packages/rsbuild-plugin/src/__tests__/atom-hoist.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/atom-hoist.test.ts @@ -52,7 +52,7 @@ compiler.hooks.thisCompilation.call(compilation); const jsTransform = transforms.find(item => item.options.test instanceof RegExp).handler; const cssTransform = transforms.find(item => item.options.test === cssDir).handler; const transform = async (file, code) => { - const result = await jsTransform({ code, resourcePath: join(root, file), addDependency() {} }); + const result = await jsTransform({ code, resourcePath: join(root, file), addDependency() {}, addMissingDependency() {} }); return result.code; }; const loadCss = name => cssTransform({ resourcePath: join(cssDir, name), environment: { name: 'web' } }); diff --git a/packages/rsbuild-plugin/src/__tests__/checkout-isolation.test.ts b/packages/rsbuild-plugin/src/__tests__/checkout-isolation.test.ts index c85723550..f3462b256 100644 --- a/packages/rsbuild-plugin/src/__tests__/checkout-isolation.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/checkout-isolation.test.ts @@ -79,6 +79,8 @@ async function extractedCssDirIn(checkout: string) { codeExtractSpy.mockClear() await transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: source, resourcePath: join(checkout, 'src', 'App.tsx'), }) diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 15afbd3ad..707cd9701 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -212,6 +212,7 @@ describe('DevupUIRsbuildPlugin', () => { ) const addDependency = mock() await transform.mock.calls[1][1]({ + addMissingDependency: mock(), code: "import { Box } from '@devup-ui/react'", resourcePath: 'src/App.tsx', addDependency, @@ -399,6 +400,8 @@ describe('DevupUIRsbuildPlugin', () => { ) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: `import { Box } from '@devup-ui/react' const App = () => `, resourcePath: 'src/App.tsx', @@ -409,6 +412,8 @@ const App = () => `, }) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: `import { Box } from '@devup-ui/react' const App = () => `, resourcePath: 'node_modules/@wrong-ui/react/index.tsx', @@ -438,6 +443,8 @@ export const a = ` ) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: source, resourcePath: 'src/App.tsx', }), @@ -468,6 +475,8 @@ export const a =
` ) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: source, resourcePath: 'src/App.tsx', }), @@ -511,6 +520,8 @@ export const a =
` }), ) const ret = await transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: `import { Box } from '@devup-ui/react' const App = () => `, resourcePath: 'src/App.tsx', @@ -527,6 +538,8 @@ const App = () => `, ) const ret1 = await transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: `import { Box } from '@devup-ui/react' const App = () => `, resourcePath: 'node_modules/@devup-ui/react/index.tsx', @@ -578,6 +591,7 @@ const App = () => `, codeExtractSpy.mockReturnValue(createCodeExtractResult()) const addDependency = mock() await transform.mock.calls[1][1]({ + addMissingDependency: mock(), code: "import { Box } from '@devup-ui/react'", resourcePath: 'src/App.tsx', addDependency, @@ -587,6 +601,71 @@ const App = () => `, readFileSyncSpy.mockRestore() readFileSpy.mockResolvedValue('{}') }) + it('watches the configs devup.json extends and reloads when one changes or is deleted', async () => { + const base = resolve('themes/base.json') + const statSpy = spyOn(fsPromises, 'stat') + try { + const present = new Set(['devup.json', base]) + existsSyncSpy.mockImplementation( + (path: string) => present.has(path) || path === resolve('devup.json'), + ) + readFileSpy.mockImplementation(async (path: string) => + path === 'devup.json' + ? JSON.stringify({ extends: ['./themes/base.json'] }) + : JSON.stringify({ + theme: { colors: { default: { primary: '#123456' } } }, + }), + ) + const stamps = new Map([ + [resolve('devup.json'), 1], + [base, 1], + ]) + statSpy.mockImplementation(async (path: fs.PathLike) => { + const mtimeMs = stamps.get(String(path)) + if (mtimeMs === undefined) throw new Error('gone') + return { mtimeMs } as fs.Stats + }) + const modifyRspackConfig = mock() + const transform = mock() + await DevupUI({}).setup( + createSetupContext({ modifyRspackConfig, transform }), + ) + const config: { plugins?: { apply: (compiler: unknown) => void }[] } = {} + modifyRspackConfig.mock.calls[0][0](config) + const tapPromise = mock() + config.plugins?.[0].apply({ hooks: { watchRun: { tapPromise } } }) + const watchRun = tapPromise.mock.calls[0][1] as () => Promise + + await watchRun() + registerThemeSpy.mockClear() + await watchRun() + expect(registerThemeSpy).not.toHaveBeenCalled() + stamps.set(base, 2) + await watchRun() + expect(registerThemeSpy).toHaveBeenCalledTimes(1) + present.delete(base) + stamps.delete(base) + await watchRun() + expect(registerThemeSpy).toHaveBeenCalledTimes(2) + + // Every module depends on the configs; a deleted one is watched for + // being added again + codeExtractSpy.mockReturnValue(createCodeExtractResult()) + const addDependency = mock() + const addMissingDependency = mock() + await transform.mock.calls[1][1]({ + code: "import { Box } from '@devup-ui/react'", + resourcePath: 'src/App.tsx', + addDependency, + addMissingDependency, + }) + expect(addDependency).toHaveBeenCalledWith(resolve('devup.json')) + expect(addMissingDependency).toHaveBeenCalledWith(base) + } finally { + statSpy.mockRestore() + readFileSpy.mockResolvedValue('{}') + } + }) it('registers the text of the Tailwind CSS with the theme', async () => { const readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue( '@theme { --color-brand: #0af; }', @@ -839,6 +918,7 @@ const App = () => `, const userRspack = config.tools.rspack modifyRsbuildConfig.mock.calls[0][0](config) await transform.mock.calls[1][1]({ + addMissingDependency: mock(), code: 'source', resourcePath, addDependency: mock(), @@ -983,6 +1063,8 @@ const App = () => `, // calls[1] is the source transform; atom mode posix-normalizes the // filename and passes a relative cssDir + import_main_css_in_code=true. await transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: `import { Box } from '@devup-ui/react'\nconst A = () => `, resourcePath: 'src/App.tsx', }) @@ -1146,6 +1228,7 @@ const App = () => `, // When for (const name of [first, second]) { await transform.mock.calls[1][1]({ + addMissingDependency: mock(), code: 'source', resourcePath: resolve('src', `${name}.tsx`), addDependency: mock(), diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 91dae66c8..43959b31e 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -76,10 +76,12 @@ async function writeDataFiles( 'extractCss' | 'debug' | 'include' >, compiler: DevupCompiler, -): Promise { +): Promise<{ tailwindFiles: string[]; configFiles: string[] }> { let tailwindFiles: string[] = [] + // devup.json and every config it `extends`, read or not + const inputs = new Set([resolve(options.devupFile)]) try { - const config = await loadDevupConfig(options.devupFile) + const config = await loadDevupConfig(options.devupFile, inputs) const theme = config.theme ?? {} compiler.registerTheme(withTailwindCss(theme, config)) @@ -110,7 +112,7 @@ async function writeDataFiles( ) : Promise.resolve(), ]) - return tailwindFiles + return { tailwindFiles, configFiles: [...inputs] } } /** @@ -167,7 +169,7 @@ export const DevupUI = ({ 'utf-8', ) - let tailwindFiles = await writeDataFiles( + let { tailwindFiles, configFiles } = await writeDataFiles( { package: libPackage, cssDir, @@ -179,8 +181,9 @@ export const DevupUI = ({ ) if (!extractCss) return - // The project's Tailwind CSS defines what a Tailwind class compiles to: - // read it again when it changes, and compile every module again + // devup.json, the configs it extends and the project's Tailwind CSS + // define the theme: read them again when one changes, is added or is + // deleted, and compile every module again api.modifyRspackConfig((config) => { config.plugins ??= [] config.plugins.push({ @@ -197,7 +200,7 @@ export const DevupUI = ({ async () => { const current = ( await Promise.all( - tailwindFiles.map((file) => + [...configFiles, ...tailwindFiles].map((file) => stat(file).then( (stats) => stats.mtimeMs, () => 0, @@ -206,7 +209,7 @@ export const DevupUI = ({ ) ).join() if (stamp !== undefined && stamp !== current) { - tailwindFiles = await writeDataFiles( + ;({ tailwindFiles, configFiles } = await writeDataFiles( { package: libPackage, cssDir, @@ -215,7 +218,7 @@ export const DevupUI = ({ singleCss, }, compiler, - ) + )) } stamp = current }, @@ -462,10 +465,13 @@ export const DevupUI = ({ { test: /\.(tsx|ts|js|mjs|jsx)$/, }, - async ({ code, resourcePath, addDependency }) => { + async ({ code, resourcePath, addDependency, addMissingDependency }) => { if (createNodeModulesExcludeRegex(include).test(resourcePath)) return code for (const file of tailwindFiles) addDependency(file) + for (const file of configFiles) + if (existsSync(file)) addDependency(file) + else addMissingDependency(file) // The stylesheet import is emitted relative to the importing file, as // in the next/webpack/vite loaders. An absolute cssDir would bake this // checkout's path into the emitted module, so byte-identical sources diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index f22c489e3..3c216fc04 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -486,7 +486,10 @@ describe('devupUIWebpackPlugin', () => { const plugin = new DevupUIWebpackPlugin({ ...options, engine: 'wasm' }) await plugin.writeDataFiles() - expect(loadDevupConfigSyncSpy).toHaveBeenCalledWith(options.devupFile) + expect(loadDevupConfigSyncSpy).toHaveBeenCalledWith( + options.devupFile, + expect.any(Set), + ) expect(registerThemeSpy).toHaveBeenCalledWith( _options.readFile?.theme ?? {}, ) @@ -585,7 +588,7 @@ describe('devupUIWebpackPlugin', () => { readFileSyncSpy.mockImplementation(() => { throw new Error('error') }) - statSpy.mockReturnValue(createStats(1)) + statSpy.mockResolvedValue(createStats(1)) existsSyncSpy.mockReturnValue(true) plugin.apply(asCompiler(compiler)) await compiler.hooks.watchRun.tapPromise.mock.calls[0][1]() @@ -594,12 +597,63 @@ describe('devupUIWebpackPlugin', () => { expect(importFileMapSpy).toHaveBeenCalledWith({}) }) + it('watches the configs devup.json extends and reloads when one changes', async () => { + const base = resolve('themes/base.json') + loadDevupConfigSyncSpy.mockImplementation( + (path: string, inputs?: Set) => { + inputs?.add(resolve(path)) + inputs?.add(base) + return {} + }, + ) + existsSyncSpy.mockImplementation( + (path: string) => path === resolve('devup.json') || path === base, + ) + const stamps = new Map([ + [resolve('devup.json'), 1], + [base, 1], + ]) + statSpy.mockImplementation(async (path: string) => + createStats(stamps.get(path) ?? 0), + ) + const plugin = new DevupUIWebpackPlugin({ engine: 'wasm', watch: true }) + const compiler = createCompiler() + plugin.apply(asCompiler(compiler)) + expect(plugin.configFiles).toEqual([resolve('devup.json'), base]) + + const add = mock() + compiler.hooks.afterCompile.tap.mock.calls[0][1]({ + fileDependencies: { add }, + missingDependencies: { add: mock() }, + }) + expect(add).toHaveBeenCalledWith(base) + + const watchRun = compiler.hooks.watchRun.tapPromise.mock.calls.find( + ([name]) => name === 'DevupUIWebpackPlugin', + )?.[1] as () => Promise + await watchRun() + loadDevupConfigSyncSpy.mockClear() + await watchRun() + expect(loadDevupConfigSyncSpy).not.toHaveBeenCalled() + + // Editing the base theme reloads; so does deleting it + stamps.set(base, 2) + await watchRun() + expect(loadDevupConfigSyncSpy).toHaveBeenCalledTimes(1) + stamps.delete(base) + await watchRun() + expect(loadDevupConfigSyncSpy).toHaveBeenCalledTimes(2) + }) + describe('Tailwind CSS definitions', () => { const tailwindFile = resolve('styles/tailwind.css') function mockTailwindCss() { existsSyncSpy.mockImplementation( - (path: string) => path === 'devup.json' || path === tailwindFile, + (path: string) => + path === 'devup.json' || + path === resolve('devup.json') || + path === tailwindFile, ) loadDevupConfigSyncSpy.mockReturnValue({ tailwind: { css: 'styles/tailwind.css' }, @@ -686,7 +740,8 @@ describe('devupUIWebpackPlugin', () => { const compiler = createCompiler() existsSyncSpy.mockImplementation((path: string) => { - if (path === plugin.options.devupFile) return options.existsDevupFile + if (path === resolve(plugin.options.devupFile)) + return options.existsDevupFile if (path === plugin.options.distDir) return options.existsDistDir if (path === plugin.options.cssDir) return options.existsCssDir if (path === join(plugin.options.distDir, 'sheet.json')) @@ -750,23 +805,20 @@ describe('devupUIWebpackPlugin', () => { expect(compiler.hooks.watchRun.tapPromise).toHaveBeenCalled() await compiler.hooks.watchRun.tapPromise.mock.calls[0][1]() - if (options.existsDevupFile) { - expect(statSpy).toHaveBeenCalledWith(plugin.options.devupFile) - await compiler.hooks.watchRun.tapPromise.mock.calls[0][1]() - } else { - expect(statSpy).not.toHaveBeenCalled() - } + // A devup.json that does not exist yet is watched for being added + expect(statSpy).toHaveBeenCalledWith(resolve(plugin.options.devupFile)) + await compiler.hooks.watchRun.tapPromise.mock.calls[0][1]() } else expect(compiler.hooks.watchRun.tapPromise).toHaveBeenCalledTimes(1) - if (options.existsDevupFile) { - expect(compiler.hooks.afterCompile.tap).toHaveBeenCalled() - const add = mock() - compiler.hooks.afterCompile.tap.mock.calls[0][1]({ - fileDependencies: { - add, - }, - }) - expect(add).toHaveBeenCalledWith(resolve(plugin.options.devupFile)) - } else expect(compiler.hooks.afterCompile.tap).not.toHaveBeenCalled() + expect(compiler.hooks.afterCompile.tap).toHaveBeenCalled() + const add = mock() + const addMissing = mock() + compiler.hooks.afterCompile.tap.mock.calls[0][1]({ + fileDependencies: { add }, + missingDependencies: { add: addMissing }, + }) + expect(options.existsDevupFile ? add : addMissing).toHaveBeenCalledWith( + resolve(plugin.options.devupFile), + ) if (options.existsCssDir) { expect(mkdirSpy).not.toHaveBeenCalledWith(plugin.options.cssDir, { recursive: true, diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 2c5bd2ed0..9e5c7ad13 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -141,9 +141,16 @@ export class DevupUIWebpackPlugin { /** The files the project's Tailwind CSS is read from */ tailwindFiles: string[] = [] + /** + * devup.json and every config it `extends`, read or not: editing, adding + * or deleting one reloads the theme + */ + configFiles: string[] = [] + writeDataFiles() { + const inputs = new Set() try { - const config = loadDevupConfigSync(this.options.devupFile) + const config = loadDevupConfigSync(this.options.devupFile, inputs) const theme = config.theme ?? {} this.compiler.registerTheme(withTailwindCss(theme, config)) @@ -160,6 +167,10 @@ export class DevupUIWebpackPlugin { } catch (error) { console.error(error) this.compiler.registerTheme({}) + } finally { + this.configFiles = [ + ...new Set([resolve(this.options.devupFile), ...inputs]), + ] } if (!existsSync(this.options.cssDir)) mkdirSync(this.options.cssDir, { recursive: true }) @@ -246,8 +257,6 @@ export class DevupUIWebpackPlugin { this.compiler.setDebug(this.options.debug) this.compiler.setPrefix(this.options.prefix ?? null) this.compiler.registerShorthands(this.normalizedShorthands) - const existsDevup = existsSync(this.options.devupFile) - // read devup.json if (!existsSync(this.options.distDir)) mkdirSync(this.options.distDir, { recursive: true }) writeFileSync(join(this.options.distDir, '.gitignore'), '*', 'utf-8') @@ -408,9 +417,7 @@ export class DevupUIWebpackPlugin { let lastModifiedTime: string | null = null compiler.hooks.watchRun.tapPromise('DevupUIWebpackPlugin', async () => { const stamps: number[] = [] - if (existsDevup) - stamps.push((await stat(this.options.devupFile)).mtimeMs) - for (const file of this.tailwindFiles) { + for (const file of [...this.configFiles, ...this.tailwindFiles]) { stamps.push( await stat(file).then( (stats) => stats.mtimeMs, @@ -418,23 +425,21 @@ export class DevupUIWebpackPlugin { ), ) } - if (stamps.length > 0) { - const modifiedTime = stamps.join() - if (lastModifiedTime && lastModifiedTime !== modifiedTime) - this.writeDataFiles() - - lastModifiedTime = modifiedTime - } + const modifiedTime = stamps.join() + if (lastModifiedTime && lastModifiedTime !== modifiedTime) + this.writeDataFiles() + lastModifiedTime = modifiedTime reserve(compiler.options) }) } - if (existsDevup || this.tailwindFiles.length > 0) - compiler.hooks.afterCompile.tap('DevupUIWebpackPlugin', (compilation) => { - if (existsDevup) - compilation.fileDependencies.add(resolve(this.options.devupFile)) - for (const file of this.tailwindFiles) - compilation.fileDependencies.add(resolve(file)) - }) + compiler.hooks.afterCompile.tap('DevupUIWebpackPlugin', (compilation) => { + // A config that does not exist yet is watched for being added + for (const file of this.configFiles) + if (existsSync(file)) compilation.fileDependencies.add(file) + else compilation.missingDependencies.add(file) + for (const file of this.tailwindFiles) + compilation.fileDependencies.add(resolve(file)) + }) compiler.options.plugins.push( new compiler.webpack.DefinePlugin({ 'process.env.DEVUP_UI_DEFAULT_THEME': JSON.stringify(