fix: unable to load CommonJS in vite plugin (#3204)
Vite has an internal check that limits CommonJS detection to only bare specifier. This doesn't work well together with us resolving npm modules to absolute file paths. https://github.com/vitejs/vite/blob/main/packages/vite/src/node/ssr/fetchModule.ts#L46 I've tried re-using our own instance of `@rollup/plugin-commonjs` or `esbuild` but couldn't get these to work in that setup. The easiest way seems to be to just write our own CJS -> ESM translation layer. With a little luck since the Deno ecosystem is heavy into ESM we might get away with this. In either way this removes one of the two blockers to using the vite plugin.
This commit is contained in:
@@ -0,0 +1,206 @@
|
||||
import type { Plugin } from "vite";
|
||||
import * as babel from "@babel/core";
|
||||
|
||||
export function commonjs(): Plugin {
|
||||
return {
|
||||
name: "cjs",
|
||||
applyToEnvironment() {
|
||||
return true;
|
||||
},
|
||||
transform(code, id) {
|
||||
const res = babel.transformSync(code, {
|
||||
filename: id,
|
||||
babelrc: false,
|
||||
plugins: [cjsPlugin],
|
||||
});
|
||||
|
||||
if (res?.code) {
|
||||
return {
|
||||
code: res.code,
|
||||
map: res.map,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function cjsPlugin(
|
||||
{ types: t }: { types: typeof babel.types },
|
||||
): babel.PluginObj {
|
||||
const HAS_ES_MODULE = "esModule";
|
||||
const REQUIRE_CALLS = "requireCalls";
|
||||
const ROOT_SCOPE = "rootScope";
|
||||
|
||||
return {
|
||||
name: "fresh-cjs-esm",
|
||||
visitor: {
|
||||
Program: {
|
||||
enter(path, state) {
|
||||
state.set(ROOT_SCOPE, path.scope);
|
||||
},
|
||||
exit(path, state) {
|
||||
const body = path.get("body");
|
||||
|
||||
const requires = state.get(REQUIRE_CALLS);
|
||||
if (requires !== undefined) {
|
||||
for (let i = 0; i < requires.length; i++) {
|
||||
const { specifier, id } = requires[i];
|
||||
path.unshiftContainer(
|
||||
"body",
|
||||
t.importDeclaration(
|
||||
[t.importNamespaceSpecifier(id)],
|
||||
specifier,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (body.length === 0 && state.get(HAS_ES_MODULE)) {
|
||||
path.pushContainer("body", t.exportNamedDeclaration(null));
|
||||
}
|
||||
},
|
||||
},
|
||||
CallExpression(path, state) {
|
||||
if (isObjEsModuleFlag(t, path.node)) {
|
||||
state.set(HAS_ES_MODULE, true);
|
||||
path.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
t.isIdentifier(path.node.callee) &&
|
||||
path.node.callee.name === "require"
|
||||
) {
|
||||
const root = state.get(ROOT_SCOPE);
|
||||
const id = root.generateUidIdentifier("mod");
|
||||
|
||||
const mods = state.get(REQUIRE_CALLS) ?? [];
|
||||
state.set(REQUIRE_CALLS, mods);
|
||||
|
||||
mods.push({
|
||||
id,
|
||||
specifier: t.cloneNode(path.node.arguments[0], true),
|
||||
});
|
||||
|
||||
if (
|
||||
path.parentPath?.isVariableDeclarator() &&
|
||||
path.parentPath?.get("id").isIdentifier() ||
|
||||
path.parentPath?.isCallExpression()
|
||||
) {
|
||||
path.replaceWith(
|
||||
t.logicalExpression(
|
||||
"??",
|
||||
t.memberExpression(
|
||||
t.cloneNode(id, true),
|
||||
t.identifier("default"),
|
||||
),
|
||||
t.cloneNode(id, true),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
path.replaceWith(t.cloneNode(id, true));
|
||||
}
|
||||
},
|
||||
ExpressionStatement(path, state) {
|
||||
const expr = path.get("expression");
|
||||
if (expr.isAssignmentExpression()) {
|
||||
const left = expr.get("left");
|
||||
|
||||
if (isEsModuleFlag(t, expr.node)) {
|
||||
state.set(HAS_ES_MODULE, true);
|
||||
path.remove();
|
||||
} else if (left.isMemberExpression()) {
|
||||
if (isModuleExports(t, left.node)) {
|
||||
const right = t.cloneNode(expr.node.right, true);
|
||||
|
||||
path.replaceWith(t.exportDefaultDeclaration(right));
|
||||
} else {
|
||||
const named = getExportsAssignName(t, left.node);
|
||||
if (named === null) return;
|
||||
|
||||
const right = t.cloneNode(expr.node.right, true);
|
||||
|
||||
if (named === "default") {
|
||||
path.replaceWith(t.exportDefaultDeclaration(right));
|
||||
} else {
|
||||
path.scope.rename(named);
|
||||
path.replaceWith(
|
||||
t.exportNamedDeclaration(
|
||||
t.variableDeclaration("let", [
|
||||
t.variableDeclarator(t.identifier(named), right),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isModuleExports(
|
||||
t: typeof babel.types,
|
||||
node: babel.types.MemberExpression,
|
||||
): boolean {
|
||||
return t.isIdentifier(node.object) && node.object.name === "module" &&
|
||||
t.isIdentifier(node.property) && node.property.name === "exports";
|
||||
}
|
||||
|
||||
function getExportsAssignName(
|
||||
t: typeof babel.types,
|
||||
node: babel.types.MemberExpression,
|
||||
): string | null {
|
||||
if (
|
||||
(t.isMemberExpression(node.object) &&
|
||||
isModuleExports(t, node.object) ||
|
||||
t.isIdentifier(node.object) && node.object.name === "exports") &&
|
||||
t.isIdentifier(node.property)
|
||||
) {
|
||||
return node.property.name;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect `exports.__esModule = true;`
|
||||
*/
|
||||
function isEsModuleFlag(
|
||||
t: typeof babel.types,
|
||||
node: babel.types.AssignmentExpression,
|
||||
): boolean {
|
||||
if (!t.isMemberExpression(node.left)) return false;
|
||||
|
||||
const { left, right } = node;
|
||||
return (t.isMemberExpression(left.object) &&
|
||||
isModuleExports(t, left.object) ||
|
||||
t.isIdentifier(left.object) && left.object.name === "exports") &&
|
||||
t.isIdentifier(left.property) && left.property.name === "__esModule" &&
|
||||
t.isBooleanLiteral(right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for `Object.defineProperty(exports, '__esModule', { value: true })`
|
||||
*/
|
||||
function isObjEsModuleFlag(
|
||||
t: typeof babel.types,
|
||||
node: babel.types.CallExpression,
|
||||
): boolean {
|
||||
return t.isMemberExpression(node.callee) &&
|
||||
t.isIdentifier(node.callee.object) &&
|
||||
node.callee.object.name === "Object" &&
|
||||
t.isIdentifier(node.callee.property) &&
|
||||
node.callee.property.name === "defineProperty" &&
|
||||
node.arguments.length === 3 &&
|
||||
(t.isMemberExpression(node.arguments[0]) &&
|
||||
isModuleExports(t, node.arguments[0]) ||
|
||||
t.isIdentifier(node.arguments[0]) &&
|
||||
node.arguments[0].name === "exports") &&
|
||||
t.isStringLiteral(node.arguments[1]) &&
|
||||
node.arguments[1].value === "__esModule" &&
|
||||
t.isObjectExpression(node.arguments[2]);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { expect } from "@std/expect/expect";
|
||||
import * as babel from "@babel/core";
|
||||
import { cjsPlugin } from "./commonjs.ts";
|
||||
|
||||
function runTest(options: { input: string; expected: string }) {
|
||||
const res = babel.transformSync(options.input, {
|
||||
filename: "foo.js",
|
||||
babelrc: false,
|
||||
plugins: [cjsPlugin],
|
||||
});
|
||||
|
||||
const output = res?.code ?? "";
|
||||
expect(output).toEqual(options.expected);
|
||||
}
|
||||
|
||||
Deno.test("commonjs - module.exports default", () => {
|
||||
runTest({
|
||||
input: `module.exports = async function () {};`,
|
||||
expected: "export default (async function () {});",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - module.exports default primitive", () => {
|
||||
runTest({
|
||||
input: `module.exports = 42;`,
|
||||
expected: "export default 42;",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - exports with default + named", () => {
|
||||
runTest({
|
||||
input: `exports.__esModule = true;
|
||||
exports.default = 'x';
|
||||
exports.foo = 'foo';`,
|
||||
expected: `export default 'x';
|
||||
export let foo = 'foo';`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - module.exports with default + named", () => {
|
||||
runTest({
|
||||
input: `module.exports.__esModule = true;
|
||||
module.exports.default = 'x';
|
||||
module.exports.foo = 'foo';`,
|
||||
expected: `export default 'x';
|
||||
export let foo = 'foo';`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - Object es module flag with named clash", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, '__esModule', { value: true });
|
||||
exports.foo = 'bar';
|
||||
const foo = 'also bar';
|
||||
`,
|
||||
expected: `export let foo = 'bar';
|
||||
const _foo = 'also bar';`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - Object es module flag with named + default", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, '__esModule', { value: true });
|
||||
exports.default = 'foo';
|
||||
exports.foo = 'bar';
|
||||
`,
|
||||
expected: `export default 'foo';
|
||||
export let foo = 'bar';`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - esModule flag only", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, "__esModule", { value: true });`,
|
||||
expected: `export {};`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - esModule flag only #2", () => {
|
||||
runTest({
|
||||
input:
|
||||
`Object.defineProperty(module.exports, "__esModule", { value: true });`,
|
||||
expected: `export {};`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - esModule flag only minified #3", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, '__esModule', { value: !0 });`,
|
||||
expected: `export {};`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - exports only named", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, '__esModule', { value: true });
|
||||
exports.foo = 'bar';
|
||||
exports.bar = 'foo';
|
||||
`,
|
||||
expected: `export let foo = 'bar';
|
||||
export let bar = 'foo';`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require", () => {
|
||||
runTest({
|
||||
input: `var foo = require("tape");
|
||||
console.log(foo);
|
||||
`,
|
||||
expected: `import * as _mod from "tape";
|
||||
var foo = _mod.default ?? _mod;
|
||||
console.log(foo);`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require destructure", () => {
|
||||
runTest({
|
||||
input: `var { foo } = require("tape");
|
||||
console.log(foo);
|
||||
`,
|
||||
expected: `import * as _mod from "tape";
|
||||
var {
|
||||
foo
|
||||
} = _mod;
|
||||
console.log(foo);`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require assign", () => {
|
||||
runTest({
|
||||
input: `foo = require("tape");
|
||||
console.log(foo);
|
||||
`,
|
||||
expected: `import * as _mod from "tape";
|
||||
foo = _mod;
|
||||
console.log(foo);`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require assign pattern", () => {
|
||||
runTest({
|
||||
input: `foo = require("tape");
|
||||
console.log(foo);
|
||||
`,
|
||||
expected: `import * as _mod from "tape";
|
||||
foo = _mod;
|
||||
console.log(foo);`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require function call", () => {
|
||||
runTest({
|
||||
input: `var a = require('./a')()`,
|
||||
expected: `import * as _mod from './a';
|
||||
var a = (_mod.default ?? _mod)();`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require var decls", () => {
|
||||
runTest({
|
||||
input: `var a = require('./a'), b = 42;`,
|
||||
expected: `import * as _mod from './a';
|
||||
var a = _mod.default ?? _mod,
|
||||
b = 42;`,
|
||||
});
|
||||
});
|
||||
|
||||
// I've never seen this, seems rare. Skipping for now.
|
||||
Deno.test.ignore("commonjs - require", () => {
|
||||
runTest({
|
||||
input: `module.exports = { __esModule: true, default: { foo: 'bar' }}`,
|
||||
expected: `import * as foo from "tape";
|
||||
console.log(foo)`,
|
||||
});
|
||||
});
|
||||
|
||||
// TODO
|
||||
Deno.test.ignore("commonjs - export default object", () => {
|
||||
runTest({
|
||||
input: `Object.defineProperty(exports, '__esModule', { value: true });
|
||||
module.exports = { foo: 'bar' };
|
||||
`,
|
||||
expected: `export let foo = 'bar';
|
||||
export let bar = 'foo';`,
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user