Skip to content

Commit 95e0e5b

Browse files
committed
chore: use require.context for auto-discovering example pages
1 parent 515070e commit 95e0e5b

4 files changed

Lines changed: 28 additions & 26 deletions

File tree

example/metro.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const root = path.resolve(__dirname, '..');
66

77
const config = getDefaultConfig(__dirname);
88
config.resolver.assetExts = [...config.resolver.assetExts, 'riv'];
9+
config.transformer.unstable_allowRequireContext = true;
910
/**
1011
* Metro configuration
1112
* https://facebook.github.io/metro/docs/configuration

example/src/PagesList.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
import type { Metadata } from './helpers/metadata';
2-
import * as Pages from './pages';
32

4-
type PageIds = keyof typeof Pages;
53
type PageType = React.ComponentType & { metadata?: Metadata };
64

7-
const PageEntries = Object.entries(Pages) as [PageIds, PageType][];
8-
95
export type PageItem = {
10-
id: PageIds;
6+
id: string;
117
name: string;
128
description: string;
139
component: React.ComponentType;
1410
};
1511

16-
const PagesList: PageItem[] = PageEntries.map(([key, Component]) => ({
17-
id: key,
18-
name: Component.metadata?.name ?? key,
19-
description: Component.metadata?.description ?? '',
20-
component: Component,
21-
}));
12+
const pagesContext = require.context('./pages', false, /\.tsx$/);
13+
14+
export const PagesList: PageItem[] = pagesContext.keys().map((key) => {
15+
const module = pagesContext(key) as { default: PageType };
16+
const Component = module.default;
17+
const id = key.replace(/^\.\//, '').replace(/\.tsx$/, '');
2218

23-
export { PagesList };
19+
return {
20+
id,
21+
name: Component.metadata?.name ?? id,
22+
description: Component.metadata?.description ?? '',
23+
component: Component,
24+
};
25+
});

example/src/pages/index.ts

Lines changed: 0 additions & 14 deletions
This file was deleted.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
interface RequireContext {
2+
keys(): string[];
3+
<T = unknown>(id: string): T;
4+
resolve(id: string): string;
5+
}
6+
7+
interface NodeRequire {
8+
context(
9+
directory: string,
10+
useSubdirectories?: boolean,
11+
regExp?: RegExp
12+
): RequireContext;
13+
}

0 commit comments

Comments
 (0)