Skip to content

Commit

Permalink
[internal] Use the Node.js behavior for default imports
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Feb 12, 2021
1 parent 4e2f830 commit 7ec6f2c
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 6 deletions.
39 changes: 39 additions & 0 deletions babel.config.js
Expand Up @@ -125,6 +125,7 @@ module.exports = function (api) {

convertESM ? "@babel/proposal-export-namespace-from" : null,
convertESM ? "@babel/transform-modules-commonjs" : null,
convertESM ? pluginDefaultImportNode : null,

pluginPackageJsonMacro,

Expand Down Expand Up @@ -382,3 +383,41 @@ function pluginPackageJsonMacro({ types: t }) {
},
};
}

// Match the Node.js behavior (the default import is module.exports)
function pluginDefaultImportNode({ types: t }) {
return {
visitor: {
ImportDeclaration(path) {
const specifiers = path.get("specifiers");
if (
specifiers.length === 0 ||
!specifiers[0].isImportDefaultSpecifier()
) {
return;
}

const { source } = path.node;
if (
source.value.startsWith(".") ||
source.value.startsWith("@babel/")
) {
// For internal modules, it's either "all CJS" or "all ESM".
// We don't need to worry about interop.
return;
}

path.insertAfter(
t.variableDeclaration("const", [
t.variableDeclarator(
specifiers[0].node.local,
t.callExpression(t.identifier("require"), [path.node.source])
),
])
);

specifiers[0].remove();
},
},
};
}
Expand Up @@ -13,11 +13,13 @@ import assert from "assert";
import fs from "fs";
import path from "path";
import vm from "vm";
import checkDuplicatedNodes from "babel-check-duplicated-nodes";
import QuickLRU from "quick-lru";
import diff from "jest-diff";
import escapeRegExp from "./escape-regexp";

import _checkDuplicatedNodes from "babel-check-duplicated-nodes";
const checkDuplicatedNodes = _checkDuplicatedNodes.default;

const cachedScripts = new QuickLRU({ maxSize: 10 });
const contextModuleCache = new WeakMap();
const sharedTestContext = createContext();
Expand Down
9 changes: 4 additions & 5 deletions packages/babel-highlight/src/index.js
@@ -1,4 +1,6 @@
import jsTokens, * as jsTokensNs from "js-tokens";
import _jsTokens from "js-tokens";
const jsTokens = _jsTokens.default;

import {
isStrictReservedWord,
isKeyword,
Expand Down Expand Up @@ -138,9 +140,6 @@ if (process.env.BABEL_8_BREAKING) {
}
};
} else {
// This is only available in js-tokens@4, and not in js-tokens@6
const { matchToToken } = jsTokensNs;

/**
* RegExp to test for what seems to be a JSX tag name.
*/
Expand Down Expand Up @@ -185,7 +184,7 @@ if (process.env.BABEL_8_BREAKING) {
tokenize = function* (text: string) {
let match;
while ((match = jsTokens.exec(text))) {
const token = matchToToken(match);
const token = _jsTokens.matchToToken(match);

yield {
type: getTokenType(token, match.index, text),
Expand Down

0 comments on commit 7ec6f2c

Please sign in to comment.