-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
routerLoader.ts
51 lines (40 loc) · 1.39 KB
/
routerLoader.ts
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { loadModule, logger } from '@sentry/utils';
import { cwd } from 'process';
import { DEBUG_BUILD } from './debug-build';
import type { ReactRouterDomPkg } from './vendor/types';
function hasMatchRoutes(pkg: ReactRouterDomPkg | undefined): boolean {
return !!pkg && typeof pkg.matchRoutes === 'function';
}
/**
* Loads the router package that provides matchRoutes.
* Tries loading @remix-run/router first, then falls back to react-router-dom.
*/
export async function loadRemixRouterModule(): Promise<ReactRouterDomPkg | undefined> {
// Try loading @remix-run/router first, then fall back to react-router-dom
for (const moduleName of ['@remix-run/router', 'react-router-dom']) {
const pkg = await tryLoadRouterModule(moduleName);
if (pkg) {
return pkg;
}
}
DEBUG_BUILD && logger.warn('Could not find a router package that provides `matchRoutes`.');
return;
}
async function tryLoadRouterModule(moduleName: string): Promise<ReactRouterDomPkg | undefined> {
let pkg: ReactRouterDomPkg | undefined;
pkg = loadModule<ReactRouterDomPkg>(moduleName);
if (hasMatchRoutes(pkg)) {
return pkg;
}
try {
pkg = await import(moduleName);
} catch (e) {
pkg = await import(`${cwd()}/node_modules/${moduleName}`);
}
if (hasMatchRoutes(pkg)) {
return pkg;
} else {
DEBUG_BUILD && logger.warn(`Could not find ${moduleName} package.`);
}
return;
}