fix(vite): keep require calls in ESM file (#3433)
Detect if a file is ESM based on file extension or finding ESM-only statements. When we know that it's an ESM file we should keep `require()` calls as is, because some libraries use it as a conditional check like `npm:motion`. Fixes https://github.com/denoland/fresh/issues/3429
This commit is contained in:
@@ -2,9 +2,11 @@ import { expect } from "@std/expect/expect";
|
||||
import * as babel from "@babel/core";
|
||||
import { cjsPlugin } from "../patches/commonjs.ts";
|
||||
|
||||
function runTest(options: { input: string; expected: string }) {
|
||||
function runTest(
|
||||
options: { input: string; expected: string; filename?: string },
|
||||
) {
|
||||
const res = babel.transformSync(options.input, {
|
||||
filename: "foo.js",
|
||||
filename: options.filename ?? "foo.js",
|
||||
babelrc: false,
|
||||
plugins: [cjsPlugin],
|
||||
});
|
||||
@@ -585,3 +587,25 @@ ${DEFAULT_EXPORT}
|
||||
${DEFAULT_EXPORT_END}`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - keep require() in .mjs", () => {
|
||||
runTest({
|
||||
filename: "foo.mjs",
|
||||
input: `try { require("foo"); } catch {}`,
|
||||
expected: `try {
|
||||
require("foo");
|
||||
} catch {}`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - keep conditional require() in ESM file", () => {
|
||||
runTest({
|
||||
filename: "foo.mjs",
|
||||
input: `try { require("foo"); } catch {};
|
||||
export {};`,
|
||||
expected: `try {
|
||||
require("foo");
|
||||
} catch {}
|
||||
export {};`,
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user