2024-01-20 18:59:40 +08:00
|
|
|
import path from 'node:path';
|
|
|
|
import { pathToFileURL } from 'node:url';
|
2024-02-27 11:15:27 +00:00
|
|
|
// This file should be imported as `#import-plugin`
|
|
|
|
import { resolve as importMetaResolve } from 'import-meta-resolve';
|
2024-01-20 18:59:40 +08:00
|
|
|
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;
|
|
|
|
}
|