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 cdacbcfe2..734b9432f 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, @@ -551,6 +552,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', @@ -561,6 +564,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', @@ -590,6 +595,8 @@ export const a = ` ) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: source, resourcePath: 'src/App.tsx', }), @@ -620,6 +627,8 @@ export const a =
` ) await expect( transform.mock.calls[1][1]({ + addDependency: mock(), + addMissingDependency: mock(), code: source, resourcePath: 'src/App.tsx', }), @@ -663,6 +672,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', @@ -679,6 +690,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', @@ -730,6 +743,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, @@ -739,6 +753,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; }', @@ -1020,6 +1099,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(), @@ -1164,6 +1244,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', }) @@ -1337,6 +1419,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 3ee51ae9a..6f7f3339c 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -79,11 +79,17 @@ async function writeDataFiles( >, compiler: DevupCompiler, watching: boolean, -): Promise<{ tailwindFiles: string[]; themeError: unknown }> { +): Promise<{ + tailwindFiles: string[] + configFiles: string[] + themeError: unknown +}> { let tailwindFiles: string[] = [] let themeError: unknown + // 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 ?? {} // Watched even when the theme fails, so fixing the Tailwind CSS reloads it @@ -116,7 +122,7 @@ async function writeDataFiles( compiler.getCss(null, false), ) } - return { tailwindFiles, themeError } + return { tailwindFiles, configFiles: [...inputs], themeError } } /** @@ -176,7 +182,7 @@ export const DevupUI = ({ // `rsbuild dev` outlives a broken devup.json; every compilation reports // it until it loads again - let { tailwindFiles, themeError } = await writeDataFiles( + let { tailwindFiles, configFiles, themeError } = await writeDataFiles( { package: libPackage, cssDir, @@ -189,8 +195,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({ @@ -207,7 +214,7 @@ export const DevupUI = ({ async () => { const current = ( await Promise.all( - tailwindFiles.map((file) => + [...configFiles, ...tailwindFiles].map((file) => stat(file).then( (stats) => stats.mtimeMs, () => 0, @@ -216,17 +223,18 @@ export const DevupUI = ({ ) ).join() if (stamp !== undefined && stamp !== current) { - ;({ tailwindFiles, themeError } = await writeDataFiles( - { - package: libPackage, - cssDir, - devupFile, - distDir, - singleCss, - }, - compiler, - true, - )) + ;({ tailwindFiles, configFiles, themeError } = + await writeDataFiles( + { + package: libPackage, + cssDir, + devupFile, + distDir, + singleCss, + }, + compiler, + true, + )) } stamp = current }, @@ -499,9 +507,13 @@ export const DevupUI = ({ code, resourcePath, addDependency, + addMissingDependency, }) => { if (excludeRegex.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 7091ee2ff..788efadfd 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -541,7 +541,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 ?? {}, ) @@ -658,7 +661,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]() @@ -667,6 +670,54 @@ 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) + }) + it('fails a one-shot build on a theme error', () => { const clash = new Error( "theme: color token 'card' and shadow token 'card' both become the CSS variable --card", @@ -733,7 +784,10 @@ describe('devupUIWebpackPlugin', () => { 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' }, @@ -820,7 +874,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')) @@ -884,23 +939,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 361085e25..1f77482f8 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -143,6 +143,12 @@ 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[] = [] + /** * Why the theme is empty in watch mode: every compilation reports it until * devup.json loads again. @@ -150,8 +156,9 @@ export class DevupUIWebpackPlugin { themeError: unknown = undefined 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)) @@ -174,6 +181,10 @@ export class DevupUIWebpackPlugin { console.error(error) this.compiler.registerTheme({}) this.themeError = error + } finally { + this.configFiles = [ + ...new Set([resolve(this.options.devupFile), ...inputs]), + ] } if (!existsSync(this.options.cssDir)) mkdirSync(this.options.cssDir, { recursive: true }) @@ -285,8 +296,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') @@ -474,9 +483,7 @@ export class DevupUIWebpackPlugin { compiler.hooks.watchRun.tapPromise('DevupUIWebpackPlugin', async () => { this.removeFiles(compiler.removedFiles) 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, @@ -484,23 +491,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(