-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathgetExampleComponent.ts
More file actions
28 lines (25 loc) · 1.11 KB
/
getExampleComponent.ts
File metadata and controls
28 lines (25 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { EXAMPLES_PAGES } from "./examplePages";
import { JSX } from "react";
// Create a webpack context matching any index file in any subdirectory of Examples.
declare var require: any;
const componentsContext = require.context("../Examples", true, /index\.(js|jsx|ts|tsx)$/);
// Convert a module path to the key expected by the context.
const loadModule = (modulePath: string) => {
const relativePath = "./" + modulePath.replace(/^(\.\.\/)+Examples\//, "");
return componentsContext(relativePath);
};
export const getExampleComponent = (exampleId: string): (() => JSX.Element) => {
const exampleInfo = EXAMPLES_PAGES[exampleId];
if (!exampleInfo) {
throw new Error("cannot find example " + exampleId);
}
const filePath = exampleInfo.exampleDirectory;
const componentPath = filePath + "/index.tsx";
const mod = loadModule(componentPath);
const componentName = exampleInfo.reactComponent;
const component = mod[componentName] || mod.default;
if (!component) {
throw new Error(`Component ${componentName} not found in module ${componentPath}`);
}
return component;
};