@typestyles/next 0.0.0-unstable.bad151c39628 → 0.0.0-unstable.c58449956735

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -142,14 +142,29 @@ const css = await getTypestylesMetadata(<Home />);
142
142
 
143
143
  ## Build-time CSS + Turbopack
144
144
 
145
- To ship a static `typestyles.css` and avoid client-side `<style>` injection (uses `typestyles/build` under the hood):
145
+ To ship a static stylesheet and avoid client-side `<style>` injection (uses `typestyles/build` under the hood):
146
146
 
147
- 1. Run `buildTypestylesForNext` before `next build` to emit CSS (and optional manifest).
147
+ 1. Run **`buildTypestylesForNext({ root })`** before `next build`. It discovers the same **convention entry** as `@typestyles/vite` (see `DEFAULT_EXTRACT_MODULE_CANDIDATES` from `@typestyles/build-runner`) and by default writes **`app/typestyles.css`** plus **`app/typestyles.manifest.json`** (override paths or pass explicit `modules` when needed).
148
148
  2. Import that CSS from your root layout (e.g. `import './typestyles.css'`).
149
- 3. Wrap config with `withTypestylesExtract` from `@typestyles/next/build`.
149
+ 3. Wrap config with **`withTypestyles`** from `@typestyles/next/build` — in **production**, if a convention entry exists, it applies **`withTypestylesExtract`**; in **development** it leaves your config unchanged so the runtime stays on.
150
150
 
151
151
  `withTypestylesExtract` sets **`NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED`** via `next.config` `env` (works with **webpack and Turbopack**) and adds webpack **`DefinePlugin`** for `__TYPESTYLES_RUNTIME_DISABLED__` on client bundles when webpack runs. Example app: `examples/next-app`.
152
152
 
153
+ ### Runtime in development, zero-runtime in production
154
+
155
+ During `next dev`, keeping the client runtime **enabled** avoids tying every style tweak to a pre-build extraction step. In production, disable injection so the browser loads one cacheable stylesheet.
156
+
157
+ ```js
158
+ // next.config.mjs
159
+ import { withTypestyles } from '@typestyles/next/build';
160
+
161
+ export default withTypestyles({
162
+ transpilePackages: ['typestyles', '@typestyles/next'],
163
+ });
164
+ ```
165
+
166
+ You still typically run extraction before production builds (CI or `prebuild`). For full manual control, **`withTypestylesExtract`** remains available.
167
+
153
168
  ## API Reference
154
169
 
155
170
  ### getRegisteredCss
@@ -204,7 +219,7 @@ import { TypestylesStylesheet } from '@typestyles/next';
204
219
  // app/page.tsx
205
220
  import { styles } from 'typestyles';
206
221
 
207
- const button = styles.create('button', {
222
+ const button = styles.component('button', {
208
223
  base: {
209
224
  padding: '12px 24px',
210
225
  backgroundColor: '#0066ff',
@@ -218,7 +233,7 @@ const button = styles.create('button', {
218
233
  export default function Home() {
219
234
  return (
220
235
  <main>
221
- <button className={button('base')}>Click me</button>
236
+ <button className={button()}>Click me</button>
222
237
  </main>
223
238
  );
224
239
  }
@@ -245,7 +260,7 @@ export const spacing = tokens.create('space', {
245
260
  import { styles } from 'typestyles';
246
261
  import { colors, spacing } from './tokens';
247
262
 
248
- const card = styles.create('card', {
263
+ const card = styles.component('card', {
249
264
  base: {
250
265
  padding: spacing.md,
251
266
  backgroundColor: colors.primary,
@@ -254,7 +269,7 @@ const card = styles.create('card', {
254
269
  });
255
270
 
256
271
  export default function Page() {
257
- return <div className={card('base')}>Hello World</div>;
272
+ return <div className={card()}>Hello World</div>;
258
273
  }
259
274
  ```
260
275
 
@@ -266,9 +281,11 @@ import { tokens } from 'typestyles';
266
281
  import { getRegisteredCss } from '@typestyles/next';
267
282
 
268
283
  const darkTheme = tokens.createTheme('dark', {
269
- color: {
270
- background: '#1a1a1a',
271
- text: '#ffffff',
284
+ base: {
285
+ color: {
286
+ background: '#1a1a1a',
287
+ text: '#ffffff',
288
+ },
272
289
  },
273
290
  });
274
291
 
@@ -276,7 +293,7 @@ export default function RootLayout({ children }) {
276
293
  const css = getRegisteredCss();
277
294
 
278
295
  return (
279
- <html className={darkTheme}>
296
+ <html className={darkTheme.className}>
280
297
  <head>{css && <style dangerouslySetInnerHTML={{ __html: css }} />}</head>
281
298
  <body>{children}</body>
282
299
  </html>
@@ -284,6 +301,14 @@ export default function RootLayout({ children }) {
284
301
  }
285
302
  ```
286
303
 
304
+ ## Fonts and local files
305
+
306
+ `global.fontFace()` registers `@font-face` like any other TypeStyles global. For **Next’s pre-build extraction** (`buildTypestylesForNext`), prefer fonts under **`public/fonts/`** and a root-relative `url('/fonts/…')` in `src` so Node does not need to resolve binary imports.
307
+
308
+ For **Vite**, you can use `import file from './font.woff2?url'` and `url(\`${file}\`) format('woff2')` so production CSS points at hashed assets.
309
+
310
+ See the **Fonts** guide in the TypeStyles docs (`docs/content/docs/fonts.md`, route `/docs/fonts` on the docs site).
311
+
287
312
  ## Troubleshooting
288
313
 
289
314
  ### Flash of Unstyled Content (FOUC)
package/dist/build.cjs CHANGED
@@ -20,7 +20,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/build.ts
21
21
  var build_exports = {};
22
22
  __export(build_exports, {
23
+ DEFAULT_EXTRACT_MODULE_CANDIDATES: () => import_build_runner.DEFAULT_EXTRACT_MODULE_CANDIDATES,
23
24
  buildTypestylesForNext: () => buildTypestylesForNext,
25
+ discoverDefaultExtractModules: () => import_build_runner.discoverDefaultExtractModules,
26
+ withTypestyles: () => withTypestyles,
24
27
  withTypestylesExtract: () => withTypestylesExtract
25
28
  });
26
29
  module.exports = __toCommonJS(build_exports);
@@ -28,10 +31,30 @@ var import_promises = require("fs/promises");
28
31
  var import_node_module = require("module");
29
32
  var import_node_path = require("path");
30
33
  var import_node_url = require("url");
34
+ var import_build_runner = require("@typestyles/build-runner");
31
35
  var import_build = require("typestyles/build");
36
+ function resolveExtractModulesForNext(root, modules) {
37
+ if (modules !== void 0) {
38
+ return modules;
39
+ }
40
+ const found = (0, import_build_runner.discoverDefaultExtractModules)(root);
41
+ if (found.length === 0) {
42
+ throw new Error(
43
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`
44
+ );
45
+ }
46
+ return found;
47
+ }
32
48
  async function buildTypestylesForNext(options) {
33
- const { root, modules, cssOutFile, manifestOutFile, manifestCssPath } = options;
34
- const loaders = modules.map((mod) => {
49
+ const {
50
+ root,
51
+ modules,
52
+ cssOutFile = "app/typestyles.css",
53
+ manifestOutFile,
54
+ manifestCssPath
55
+ } = options;
56
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
57
+ const loaders = resolvedModules.map((mod) => {
35
58
  const abs = (0, import_node_path.resolve)(root, mod);
36
59
  const href = (0, import_node_url.pathToFileURL)(abs).href;
37
60
  return () => import(href);
@@ -40,19 +63,30 @@ async function buildTypestylesForNext(options) {
40
63
  const outAbs = (0, import_node_path.resolve)(root, cssOutFile);
41
64
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(outAbs), { recursive: true });
42
65
  await (0, import_promises.writeFile)(outAbs, css, "utf8");
43
- if (manifestOutFile) {
66
+ const manifestRel = manifestOutFile === false ? void 0 : manifestOutFile ?? "app/typestyles.manifest.json";
67
+ if (manifestRel) {
44
68
  const manifest = {
45
69
  version: 1,
46
70
  css: manifestCssPath ?? cssOutFile
47
71
  };
48
- const manAbs = (0, import_node_path.resolve)(root, manifestOutFile);
72
+ const manAbs = (0, import_node_path.resolve)(root, manifestRel);
49
73
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(manAbs), { recursive: true });
50
74
  await (0, import_promises.writeFile)(manAbs, `${JSON.stringify(manifest, null, 2)}
51
75
  `, "utf8");
52
76
  }
53
77
  }
78
+ function withTypestyles(nextConfig = {}, options = {}) {
79
+ const projectRoot = options.root ?? process.cwd();
80
+ const hasConventionEntry = (0, import_build_runner.discoverDefaultExtractModules)(projectRoot).length > 0;
81
+ const prod = process.env.NODE_ENV === "production";
82
+ if (!prod || !hasConventionEntry) {
83
+ return nextConfig;
84
+ }
85
+ return withTypestylesExtract(nextConfig, options);
86
+ }
54
87
  function withTypestylesExtract(nextConfig = {}, options = {}) {
55
88
  const disableClientRuntime = options.disableClientRuntime !== false;
89
+ const projectRoot = options.root ?? process.cwd();
56
90
  return {
57
91
  ...nextConfig,
58
92
  ...disableClientRuntime ? {
@@ -65,7 +99,7 @@ function withTypestylesExtract(nextConfig = {}, options = {}) {
65
99
  const nextWebpack = typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, context) : config;
66
100
  if (disableClientRuntime && !context.isServer) {
67
101
  try {
68
- const require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "package.json"));
102
+ const require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(projectRoot, "package.json"));
69
103
  const webpackLib = require2("webpack");
70
104
  nextWebpack.plugins.push(
71
105
  new webpackLib.DefinePlugin({
@@ -84,6 +118,9 @@ function withTypestylesExtract(nextConfig = {}, options = {}) {
84
118
  }
85
119
  // Annotate the CommonJS export names for ESM import in node:
86
120
  0 && (module.exports = {
121
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
87
122
  buildTypestylesForNext,
123
+ discoverDefaultExtractModules,
124
+ withTypestyles,
88
125
  withTypestylesExtract
89
126
  });
package/dist/build.js CHANGED
@@ -3,10 +3,33 @@ import { mkdir, writeFile } from "fs/promises";
3
3
  import { createRequire } from "module";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import { pathToFileURL } from "url";
6
+ import {
7
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
8
+ discoverDefaultExtractModules
9
+ } from "@typestyles/build-runner";
6
10
  import { collectStylesFromModules } from "typestyles/build";
11
+ function resolveExtractModulesForNext(root, modules) {
12
+ if (modules !== void 0) {
13
+ return modules;
14
+ }
15
+ const found = discoverDefaultExtractModules(root);
16
+ if (found.length === 0) {
17
+ throw new Error(
18
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`
19
+ );
20
+ }
21
+ return found;
22
+ }
7
23
  async function buildTypestylesForNext(options) {
8
- const { root, modules, cssOutFile, manifestOutFile, manifestCssPath } = options;
9
- const loaders = modules.map((mod) => {
24
+ const {
25
+ root,
26
+ modules,
27
+ cssOutFile = "app/typestyles.css",
28
+ manifestOutFile,
29
+ manifestCssPath
30
+ } = options;
31
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
32
+ const loaders = resolvedModules.map((mod) => {
10
33
  const abs = resolve(root, mod);
11
34
  const href = pathToFileURL(abs).href;
12
35
  return () => import(href);
@@ -15,19 +38,30 @@ async function buildTypestylesForNext(options) {
15
38
  const outAbs = resolve(root, cssOutFile);
16
39
  await mkdir(dirname(outAbs), { recursive: true });
17
40
  await writeFile(outAbs, css, "utf8");
18
- if (manifestOutFile) {
41
+ const manifestRel = manifestOutFile === false ? void 0 : manifestOutFile ?? "app/typestyles.manifest.json";
42
+ if (manifestRel) {
19
43
  const manifest = {
20
44
  version: 1,
21
45
  css: manifestCssPath ?? cssOutFile
22
46
  };
23
- const manAbs = resolve(root, manifestOutFile);
47
+ const manAbs = resolve(root, manifestRel);
24
48
  await mkdir(dirname(manAbs), { recursive: true });
25
49
  await writeFile(manAbs, `${JSON.stringify(manifest, null, 2)}
26
50
  `, "utf8");
27
51
  }
28
52
  }
53
+ function withTypestyles(nextConfig = {}, options = {}) {
54
+ const projectRoot = options.root ?? process.cwd();
55
+ const hasConventionEntry = discoverDefaultExtractModules(projectRoot).length > 0;
56
+ const prod = process.env.NODE_ENV === "production";
57
+ if (!prod || !hasConventionEntry) {
58
+ return nextConfig;
59
+ }
60
+ return withTypestylesExtract(nextConfig, options);
61
+ }
29
62
  function withTypestylesExtract(nextConfig = {}, options = {}) {
30
63
  const disableClientRuntime = options.disableClientRuntime !== false;
64
+ const projectRoot = options.root ?? process.cwd();
31
65
  return {
32
66
  ...nextConfig,
33
67
  ...disableClientRuntime ? {
@@ -40,7 +74,7 @@ function withTypestylesExtract(nextConfig = {}, options = {}) {
40
74
  const nextWebpack = typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, context) : config;
41
75
  if (disableClientRuntime && !context.isServer) {
42
76
  try {
43
- const require2 = createRequire(join(process.cwd(), "package.json"));
77
+ const require2 = createRequire(join(projectRoot, "package.json"));
44
78
  const webpackLib = require2("webpack");
45
79
  nextWebpack.plugins.push(
46
80
  new webpackLib.DefinePlugin({
@@ -58,6 +92,9 @@ function withTypestylesExtract(nextConfig = {}, options = {}) {
58
92
  };
59
93
  }
60
94
  export {
95
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
61
96
  buildTypestylesForNext,
97
+ discoverDefaultExtractModules,
98
+ withTypestyles,
62
99
  withTypestylesExtract
63
100
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typestyles/next",
3
- "version": "0.0.0-unstable.bad151c39628",
3
+ "version": "0.0.0-unstable.c58449956735",
4
4
  "description": "Next.js integration for typestyles SSR",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -67,7 +67,11 @@
67
67
  "optional": true
68
68
  }
69
69
  },
70
+ "dependencies": {
71
+ "@typestyles/build-runner": "0.0.0-unstable.c58449956735"
72
+ },
70
73
  "devDependencies": {
74
+ "eslint": "^9.39.2",
71
75
  "vitest": "^3.0.0",
72
76
  "@types/node": "^25.2.1",
73
77
  "@types/react": "^18.3.12",
@@ -76,13 +80,14 @@
76
80
  "react": "^18.0.0",
77
81
  "react-dom": "^18.0.0",
78
82
  "tsup": "^8.0.0",
79
- "typestyles": "0.0.0-unstable.bad151c39628",
83
+ "typestyles": "0.0.0-unstable.c58449956735",
80
84
  "typescript": "^5.4.0",
81
85
  "webpack": "^5.97.1"
82
86
  },
83
87
  "scripts": {
84
88
  "build": "tsup",
85
89
  "test": "vitest run",
90
+ "lint": "eslint .",
86
91
  "typecheck": "tsc --noEmit"
87
92
  }
88
93
  }
package/src/build.d.ts CHANGED
@@ -5,11 +5,15 @@ export interface TypestylesExtractManifestV1 {
5
5
  css: string;
6
6
  }
7
7
 
8
+ export declare const DEFAULT_EXTRACT_MODULE_CANDIDATES: readonly string[];
9
+
10
+ export declare function discoverDefaultExtractModules(root: string): string[];
11
+
8
12
  export interface BuildTypestylesForNextOptions {
9
13
  root: string;
10
- modules: string[];
11
- cssOutFile: string;
12
- manifestOutFile?: string;
14
+ modules?: string[];
15
+ cssOutFile?: string;
16
+ manifestOutFile?: string | false;
13
17
  manifestCssPath?: string;
14
18
  }
15
19
 
@@ -19,8 +23,18 @@ export declare function buildTypestylesForNext(
19
23
 
20
24
  export interface WithTypestylesExtractOptions {
21
25
  disableClientRuntime?: boolean;
26
+ root?: string;
27
+ }
28
+
29
+ export interface WithTypestylesOptions extends WithTypestylesExtractOptions {
30
+ root?: string;
22
31
  }
23
32
 
33
+ export declare function withTypestyles(
34
+ nextConfig?: NextConfig,
35
+ options?: WithTypestylesOptions,
36
+ ): NextConfig;
37
+
24
38
  export declare function withTypestylesExtract(
25
39
  nextConfig?: NextConfig,
26
40
  options?: WithTypestylesExtractOptions,
package/src/build.test.ts CHANGED
@@ -1,16 +1,16 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
1
4
  import { describe, it, expect, vi } from 'vitest';
2
5
  import type { NextConfig } from 'next';
3
6
  import type { Configuration } from 'webpack';
4
- import { withTypestylesExtract } from './build.js';
7
+ import { withTypestyles, withTypestylesExtract } from './build';
5
8
 
6
9
  type WebpackContext = Parameters<NonNullable<NextConfig['webpack']>>[1];
7
10
 
8
11
  describe('withTypestylesExtract', () => {
9
12
  it('merges NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED into env for Turbopack + webpack', () => {
10
- const merged = withTypestylesExtract(
11
- { env: { CUSTOM: 'x' } },
12
- { disableClientRuntime: true },
13
- );
13
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: true });
14
14
  expect(merged.env).toEqual({
15
15
  CUSTOM: 'x',
16
16
  NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
@@ -18,10 +18,7 @@ describe('withTypestylesExtract', () => {
18
18
  });
19
19
 
20
20
  it('does not override env when disableClientRuntime is false', () => {
21
- const merged = withTypestylesExtract(
22
- { env: { CUSTOM: 'x' } },
23
- { disableClientRuntime: false },
24
- );
21
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: false });
25
22
  expect(merged.env).toEqual({ CUSTOM: 'x' });
26
23
  });
27
24
 
@@ -33,9 +30,12 @@ describe('withTypestylesExtract', () => {
33
30
  });
34
31
  const merged = withTypestylesExtract({ webpack: userWebpack });
35
32
  const config = { plugins: [] as unknown[] };
36
- const result = merged.webpack!(config as Configuration, {
37
- isServer: false,
38
- } as WebpackContext);
33
+ const result = merged.webpack!(
34
+ config as Configuration,
35
+ {
36
+ isServer: false,
37
+ } as WebpackContext,
38
+ );
39
39
  expect(userWebpack).toHaveBeenCalled();
40
40
  const hasDefine = result.plugins?.some(
41
41
  (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
@@ -43,13 +43,51 @@ describe('withTypestylesExtract', () => {
43
43
  expect(hasDefine).toBe(true);
44
44
  });
45
45
 
46
+ it('applies extract in production when a convention entry exists under root', () => {
47
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-cwd-'));
48
+ mkdirSync(join(dir, 'styles'), { recursive: true });
49
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
50
+
51
+ vi.stubEnv('NODE_ENV', 'production');
52
+ try {
53
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
54
+ expect(merged.env).toEqual({
55
+ CUSTOM: 'y',
56
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
57
+ });
58
+ } finally {
59
+ vi.unstubAllEnvs();
60
+ }
61
+
62
+ rmSync(dir, { recursive: true, force: true });
63
+ });
64
+
65
+ it('does not apply extract in development even when a convention entry exists', () => {
66
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-dev-'));
67
+ mkdirSync(join(dir, 'styles'), { recursive: true });
68
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
69
+
70
+ vi.stubEnv('NODE_ENV', 'development');
71
+ try {
72
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
73
+ expect(merged.env).toEqual({ CUSTOM: 'y' });
74
+ } finally {
75
+ vi.unstubAllEnvs();
76
+ }
77
+
78
+ rmSync(dir, { recursive: true, force: true });
79
+ });
80
+
46
81
  it('does not add DefinePlugin for server bundles', async () => {
47
82
  const webpackMod = await import('webpack');
48
83
  const merged = withTypestylesExtract({});
49
84
  const config = { plugins: [] as unknown[] };
50
- const result = merged.webpack!(config as Configuration, {
51
- isServer: true,
52
- } as WebpackContext);
85
+ const result = merged.webpack!(
86
+ config as Configuration,
87
+ {
88
+ isServer: true,
89
+ } as WebpackContext,
90
+ );
53
91
  const hasDefine = result.plugins?.some(
54
92
  (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
55
93
  );
package/src/build.ts CHANGED
@@ -2,9 +2,16 @@ import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import { createRequire } from 'node:module';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import {
6
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
7
+ discoverDefaultExtractModules,
8
+ } from '@typestyles/build-runner';
5
9
  import { collectStylesFromModules } from 'typestyles/build';
6
10
  import type { NextConfig } from 'next';
7
11
 
12
+ /** Re-export shared convention paths (aligned with `@typestyles/vite`). */
13
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules };
14
+
8
15
  /** Manifest shape written next to extracted CSS (optional). */
9
16
  export interface TypestylesExtractManifestV1 {
10
17
  version: 1;
@@ -18,19 +25,56 @@ type WebpackWithDefinePlugin = {
18
25
 
19
26
  export interface BuildTypestylesForNextOptions {
20
27
  root: string;
21
- modules: string[];
22
- cssOutFile: string;
23
- manifestOutFile?: string;
28
+ /**
29
+ * Style entry modules relative to `root`. When omitted, uses the same convention discovery as
30
+ * `@typestyles/vite` (see {@link discoverDefaultExtractModules}).
31
+ */
32
+ modules?: string[];
33
+ /** Output CSS path relative to `root`. Defaults to `app/typestyles.css`. */
34
+ cssOutFile?: string;
35
+ /**
36
+ * Manifest path relative to `root`. Defaults to `app/typestyles.manifest.json`.
37
+ * Pass `false` to skip writing a manifest.
38
+ */
39
+ manifestOutFile?: string | false;
40
+ /** Value stored in the manifest `css` field. Defaults to `cssOutFile`. */
24
41
  manifestCssPath?: string;
25
42
  }
26
43
 
44
+ function resolveExtractModulesForNext(root: string, modules?: string[]): string[] {
45
+ if (modules !== undefined) {
46
+ return modules;
47
+ }
48
+ const found = discoverDefaultExtractModules(root);
49
+ if (found.length === 0) {
50
+ throw new Error(
51
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`,
52
+ );
53
+ }
54
+ return found;
55
+ }
56
+
27
57
  /**
28
58
  * Extract TypeStyles CSS for a Next.js app (run from a script before `next build`, or in CI).
29
59
  * Loads each module path (relative to `root`) so side-effect registrations run, then writes CSS.
60
+ *
61
+ * Defaults mirror `@typestyles/vite`: discovers a convention entry when `modules` is omitted,
62
+ * writes `app/typestyles.css` and `app/typestyles.manifest.json` unless overridden.
30
63
  */
31
- export async function buildTypestylesForNext(options: BuildTypestylesForNextOptions): Promise<void> {
32
- const { root, modules, cssOutFile, manifestOutFile, manifestCssPath } = options;
33
- const loaders = modules.map((mod) => {
64
+ export async function buildTypestylesForNext(
65
+ options: BuildTypestylesForNextOptions,
66
+ ): Promise<void> {
67
+ const {
68
+ root,
69
+ modules,
70
+ cssOutFile = 'app/typestyles.css',
71
+ manifestOutFile,
72
+ manifestCssPath,
73
+ } = options;
74
+
75
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
76
+
77
+ const loaders = resolvedModules.map((mod) => {
34
78
  const abs = resolve(root, mod);
35
79
  const href = pathToFileURL(abs).href;
36
80
  return () => import(href);
@@ -39,12 +83,16 @@ export async function buildTypestylesForNext(options: BuildTypestylesForNextOpti
39
83
  const outAbs = resolve(root, cssOutFile);
40
84
  await mkdir(dirname(outAbs), { recursive: true });
41
85
  await writeFile(outAbs, css, 'utf8');
42
- if (manifestOutFile) {
86
+
87
+ const manifestRel =
88
+ manifestOutFile === false ? undefined : (manifestOutFile ?? 'app/typestyles.manifest.json');
89
+
90
+ if (manifestRel) {
43
91
  const manifest: TypestylesExtractManifestV1 = {
44
92
  version: 1,
45
93
  css: manifestCssPath ?? cssOutFile,
46
94
  };
47
- const manAbs = resolve(root, manifestOutFile);
95
+ const manAbs = resolve(root, manifestRel);
48
96
  await mkdir(dirname(manAbs), { recursive: true });
49
97
  await writeFile(manAbs, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
50
98
  }
@@ -56,6 +104,37 @@ export interface WithTypestylesExtractOptions {
56
104
  * Pair with a global stylesheet from {@link buildTypestylesForNext}.
57
105
  */
58
106
  disableClientRuntime?: boolean;
107
+ /**
108
+ * Project root used for module resolution (e.g. loading `webpack`). Defaults to `process.cwd()`.
109
+ */
110
+ root?: string;
111
+ }
112
+
113
+ export interface WithTypestylesOptions extends WithTypestylesExtractOptions {
114
+ /**
115
+ * Project root for convention discovery. Defaults to `process.cwd()` (the directory Next runs from).
116
+ */
117
+ root?: string;
118
+ }
119
+
120
+ /**
121
+ * Production Next.js config helper aligned with `@typestyles/vite`: when `NODE_ENV === 'production'`
122
+ * and a convention entry file exists under `root`, applies {@link withTypestylesExtract}; otherwise
123
+ * returns `nextConfig` unchanged (development keeps runtime injection).
124
+ */
125
+ export function withTypestyles(
126
+ nextConfig: NextConfig = {},
127
+ options: WithTypestylesOptions = {},
128
+ ): NextConfig {
129
+ const projectRoot = options.root ?? process.cwd();
130
+ const hasConventionEntry = discoverDefaultExtractModules(projectRoot).length > 0;
131
+ const prod = process.env.NODE_ENV === 'production';
132
+
133
+ if (!prod || !hasConventionEntry) {
134
+ return nextConfig;
135
+ }
136
+
137
+ return withTypestylesExtract(nextConfig, options);
59
138
  }
60
139
 
61
140
  /**
@@ -71,6 +150,7 @@ export function withTypestylesExtract(
71
150
  options: WithTypestylesExtractOptions = {},
72
151
  ): NextConfig {
73
152
  const disableClientRuntime = options.disableClientRuntime !== false;
153
+ const projectRoot = options.root ?? process.cwd();
74
154
 
75
155
  return {
76
156
  ...nextConfig,
@@ -92,7 +172,7 @@ export function withTypestylesExtract(
92
172
 
93
173
  if (disableClientRuntime && !context.isServer) {
94
174
  try {
95
- const require = createRequire(join(process.cwd(), 'package.json'));
175
+ const require = createRequire(join(projectRoot, 'package.json'));
96
176
  const webpackLib = require('webpack') as WebpackWithDefinePlugin;
97
177
  nextWebpack.plugins.push(
98
178
  new webpackLib.DefinePlugin({
package/src/client.d.ts CHANGED
@@ -11,9 +11,7 @@ export function useTypestyles(): ReturnType<typeof useSyncExternalStore<string>>
11
11
  * Re-export of React’s `useServerInsertedHTML` (App Router / streaming SSR).
12
12
  * Declared here so consumers get a stable signature even when their `@types/react` predates the hook.
13
13
  */
14
- export function useServerInsertedHTML(
15
- callback: () => React.ReactNode | null,
16
- ): void;
14
+ export function useServerInsertedHTML(callback: () => React.ReactNode | null): void;
17
15
 
18
16
  /**
19
17
  * Props for the TypestylesStylesheet component.
@@ -25,9 +23,7 @@ export interface TypestylesStylesheetProps {
25
23
  /**
26
24
  * A React component that renders typestyles CSS.
27
25
  */
28
- export function TypestylesStylesheet(
29
- props: TypestylesStylesheetProps,
30
- ): React.JSX.Element | null;
26
+ export function TypestylesStylesheet(props: TypestylesStylesheetProps): React.JSX.Element | null;
31
27
 
32
28
  /**
33
29
  * Create a Next.js layout export that includes typestyles.