Skip to content

Commit ab8f4eb

Browse files
committed
Smarter path handling
1 parent f06401f commit ab8f4eb

File tree

2 files changed

+36
-8
lines changed

2 files changed

+36
-8
lines changed

src/lib/utils/plugins.ts

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,25 @@ export async function loadPlugins(
1313
const pluginDisplay = getPluginDisplayName(plugin);
1414

1515
try {
16-
// On Windows, we need to ensure this path is a file path.
17-
// Or we'll get ERR_UNSUPPORTED_ESM_URL_SCHEME
18-
const esmPath = isAbsolute(plugin)
19-
? pathToFileURL(plugin).toString()
20-
: plugin;
21-
let instance: any = await import(esmPath);
22-
const initFunction = instance.load || instance.default?.load;
16+
let instance: any;
17+
// Try importing first to avoid warnings about requiring ESM being experimental.
18+
// If that fails due to importing a directory, fall back to require.
19+
try {
20+
// On Windows, we need to ensure this path is a file path.
21+
// Or we'll get ERR_UNSUPPORTED_ESM_URL_SCHEME
22+
const esmPath = isAbsolute(plugin)
23+
? pathToFileURL(plugin).toString()
24+
: plugin;
25+
instance = await import(esmPath);
26+
} catch (error: any) {
27+
if (error.code === "ERR_UNSUPPORTED_DIR_IMPORT") {
28+
// eslint-disable-next-line @typescript-eslint/no-require-imports
29+
instance = require(plugin);
30+
} else {
31+
throw error;
32+
}
33+
}
34+
const initFunction = instance.load;
2335

2436
if (typeof initFunction === "function") {
2537
await initFunction(app);

src/test/utils/plugins.test.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ describe("loadPlugins", () => {
1414
logger = fakeApp.logger = new TestLogger();
1515
});
1616

17-
it("Should support loading a basic plugin", async () => {
17+
it("Should support loading a CJS plugin with directory target", async () => {
1818
using project = tempdirProject();
1919
project.addJsonFile("package.json", {
2020
type: "commonjs",
@@ -28,6 +28,22 @@ describe("loadPlugins", () => {
2828
logger.expectMessage(`info: Loaded plugin ${plugin}`);
2929
});
3030

31+
it("Should support loading a CJS plugin with full path", async () => {
32+
using project = tempdirProject();
33+
project.addJsonFile("package.json", {
34+
type: "commonjs",
35+
main: "index.js",
36+
});
37+
const plugin = project.addFile(
38+
"index.js",
39+
"exports.load = function load() {}",
40+
).path;
41+
project.write();
42+
43+
await loadPlugins(fakeApp, [plugin]);
44+
logger.expectMessage(`info: Loaded plugin ${plugin}`);
45+
});
46+
3147
it("Should support loading a ESM plugin", async () => {
3248
using project = tempdirProject();
3349
project.addJsonFile("package.json", {

0 commit comments

Comments
 (0)