From a8a0afa562468394c95c209798bf5eedd18a7111 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Ribaudo?= Date: Sun, 1 Mar 2020 22:16:01 +0100 Subject: [PATCH] Make tests pass --- babel.config.js | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/babel.config.js b/babel.config.js index 1ec169604ab5..5cb6ab5cde32 100644 --- a/babel.config.js +++ b/babel.config.js @@ -12,6 +12,8 @@ module.exports = function(api) { }; const envOpts = Object.assign({}, envOptsNoTargets); + const compileDynamicImport = env === "test" || env === "development"; + let convertESM = true; let ignoreLib = true; let includeRegeneratorRuntime = false; @@ -107,10 +109,6 @@ module.exports = function(api) { ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: true }], convertESM ? "@babel/transform-modules-commonjs" : null, - // Until Jest supports native mjs, we must simulate it 🤷 - env === "test" || env === "development" - ? "@babel/plugin-proposal-dynamic-import" - : null, ].filter(Boolean), overrides: [ { @@ -141,6 +139,15 @@ module.exports = function(api) { exclude: /regenerator-runtime/, plugins: [["@babel/transform-runtime", transformRuntimeOptions]], }, + compileDynamicImport && { + // Until Jest supports native mjs, we must simulate it 🤷 + + test: "./packages/babel-core/src/config/files/import.js", + plugins: [ + dynamicImportUrlToPath, + "@babel/plugin-proposal-dynamic-import", + ], + }, ].filter(Boolean), }; @@ -152,3 +159,28 @@ module.exports = function(api) { return config; }; + +// import() uses file:// URLs for absolute imports, while require() uses +// file paths. +// Since this isn't handled by @babel/plugin-transform-modules-commonjs, +// we must handle it here. +// NOTE: This plugin must run before @babel/plugin-transform-modules-commonjs +function dynamicImportUrlToPath({ template }) { + return { + visitor: { + Program(path) { + path.traverse({ + CallExpression(path) { + if (path.get("callee").isImport()) { + path.get("arguments.0").replaceWith( + template.expression.ast` + require("url").fileURLToPath(${path.node.arguments[0]}) + ` + ); + } + }, + }); + }, + }, + }; +}