summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/import-plugin-default.ts
blob: ede7cba7d8cc5288c8572b9602a68cb849b30c2f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// This file should be imported as `#import-plugin`
import { resolve as importMetaResolve } from 'import-meta-resolve';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import type * as unified from 'unified';

let cwdUrlStr: string | undefined;

// In non-browser enviroments, we can try to resolve from the filesystem too
export async function importPlugin(p: string): Promise<unified.Plugin> {
	// Try import from this package first
	try {
		const importResult = await import(p);
		return importResult.default;
	} catch {}

	// Try import from user project
	cwdUrlStr ??= pathToFileURL(path.join(process.cwd(), 'package.json')).toString();
	const resolved = importMetaResolve(p, cwdUrlStr);
	const importResult = await import(resolved);
	return importResult.default;
}