From a65ce33fabb44bb2d9ed04773f7f334ed9c9a6b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 27 Feb 2022 14:38:45 +0100 Subject: feat(compat): CJS/ESM interoperability (#13553) This commit adds CJS/ESM interoperability when running in --compat mode. Before executing files, they are analyzed and all CommonJS modules are transformed on the fly to a ES modules. This is done by utilizing analyze_cjs() functionality from deno_ast. After discovering exports and reexports, an ES module is rendered and saved in memory for later use. There's a caveat that all files ending with ".js" extension are considered as CommonJS modules (unless there's a related "package.json" with "type": "module"). --- cli/tests/testdata/compat/import_cjs_from_esm/imported.js | 9 +++++++++ cli/tests/testdata/compat/import_cjs_from_esm/main.mjs | 1 + cli/tests/testdata/compat/import_cjs_from_esm/reexports.js | 1 + cli/tests/testdata/compat/import_cjs_from_esm/reexports2.js | 2 ++ 4 files changed, 13 insertions(+) create mode 100644 cli/tests/testdata/compat/import_cjs_from_esm/imported.js create mode 100644 cli/tests/testdata/compat/import_cjs_from_esm/main.mjs create mode 100644 cli/tests/testdata/compat/import_cjs_from_esm/reexports.js create mode 100644 cli/tests/testdata/compat/import_cjs_from_esm/reexports2.js (limited to 'cli/tests/testdata/compat/import_cjs_from_esm') diff --git a/cli/tests/testdata/compat/import_cjs_from_esm/imported.js b/cli/tests/testdata/compat/import_cjs_from_esm/imported.js new file mode 100644 index 000000000..49ab4c782 --- /dev/null +++ b/cli/tests/testdata/compat/import_cjs_from_esm/imported.js @@ -0,0 +1,9 @@ +exports = { + a: "A", + b: "B", +}; +exports.foo = "foo"; +exports.bar = "bar"; +exports.fizz = require("./reexports.js"); + +console.log(exports); diff --git a/cli/tests/testdata/compat/import_cjs_from_esm/main.mjs b/cli/tests/testdata/compat/import_cjs_from_esm/main.mjs new file mode 100644 index 000000000..6fbed1b7c --- /dev/null +++ b/cli/tests/testdata/compat/import_cjs_from_esm/main.mjs @@ -0,0 +1 @@ +import "./imported.js"; diff --git a/cli/tests/testdata/compat/import_cjs_from_esm/reexports.js b/cli/tests/testdata/compat/import_cjs_from_esm/reexports.js new file mode 100644 index 000000000..62edb7708 --- /dev/null +++ b/cli/tests/testdata/compat/import_cjs_from_esm/reexports.js @@ -0,0 +1 @@ +module.exports = require("./reexports2.js"); diff --git a/cli/tests/testdata/compat/import_cjs_from_esm/reexports2.js b/cli/tests/testdata/compat/import_cjs_from_esm/reexports2.js new file mode 100644 index 000000000..183d833b0 --- /dev/null +++ b/cli/tests/testdata/compat/import_cjs_from_esm/reexports2.js @@ -0,0 +1,2 @@ +exports.buzz = "buzz"; +exports.fizz = "FIZZ"; -- cgit v1.2.3