Skip to content

Commit fcb44e6

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

4 files changed

Lines changed: 42 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: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Based on https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/webpack-env/index.d.ts
2+
// Adds support for the runtime `require.context` method.
3+
// https://github.com/facebook/metro/pull/822/
4+
5+
declare namespace __MetroModuleApi {
6+
interface RequireContext {
7+
keys(): string[];
8+
(id: string): any;
9+
<T>(id: string): T;
10+
resolve(id: string): string;
11+
}
12+
13+
interface RequireFunction {
14+
(path: string): any;
15+
<T>(path: string): T;
16+
context(
17+
path: string,
18+
recursive?: boolean,
19+
filter?: RegExp,
20+
mode?: 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once'
21+
): RequireContext;
22+
}
23+
}
24+
25+
declare namespace NodeJS {
26+
interface Require extends __MetroModuleApi.RequireFunction {}
27+
}

0 commit comments

Comments
 (0)