client-bundle-css.spec.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * CSS Modules enter client bundles through virtual modules, so the loader must
  3. * explicitly register the underlying stylesheet as a watch dependency.
  4. */
  5. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  6. import { tmpdir } from 'node:os'
  7. import { join } from 'node:path'
  8. import { describe, expect, it } from 'vitest'
  9. import { clientBundle } from '../packages/client/tsdown.client.ts'
  10. interface CssPlugin {
  11. name: string
  12. resolveId?: (source: string, importer?: string) => string | null
  13. load?: (this: { addWatchFile(id: string): void }, id: string) => Promise<string | null>
  14. }
  15. function cssPlugin(): CssPlugin {
  16. const configs = clientBundle(
  17. '@deepseek-ai/dsh-client-test',
  18. ['lib/types/index.js', 'lib/types/invariant.js'],
  19. )({ env: { DSH_BUILD_FACE: 'client' } })
  20. const client = configs.find(config => config.platform === 'browser')
  21. if (client === undefined) throw new Error('client config missing')
  22. const plugins = (client as { plugins: CssPlugin[] }).plugins
  23. const plugin = plugins.find(candidate => candidate.name === 'dsh-css-modules-inline')
  24. if (plugin === undefined) throw new Error('CSS Modules plugin missing from client config')
  25. return plugin
  26. }
  27. describe('client bundle CSS Modules', () => {
  28. it('registers the source stylesheet as a watch dependency', async () => {
  29. const root = await mkdtemp(join(tmpdir(), 'dsh-client-css-watch-'))
  30. try {
  31. const stylesheet = join(root, 'Fixture.module.css')
  32. const importer = join(root, 'index.ts')
  33. await writeFile(stylesheet, '.root { color: red; }\n')
  34. const plugin = cssPlugin()
  35. const virtualId = plugin.resolveId?.('./Fixture.module.css', importer)
  36. if (typeof virtualId !== 'string' || plugin.load === undefined) {
  37. throw new Error('CSS Modules plugin hooks are incomplete')
  38. }
  39. const watched: string[] = []
  40. const output = await plugin.load.call({ addWatchFile: id => watched.push(id) }, virtualId)
  41. expect(watched).toEqual([stylesheet])
  42. expect(output).toContain('data-plugin-css')
  43. } finally {
  44. await rm(root, { recursive: true, force: true })
  45. }
  46. })
  47. })