Use the imports helper in transform-runtime.

This commit is contained in:
Logan Smyth
2017-09-20 09:32:14 -07:00
parent 11715cb7af
commit ed3603ef44
22 changed files with 150 additions and 47 deletions

View File

@@ -1,3 +1,5 @@
import { addDefault, isModule } from "babel-helper-module-imports";
import definitions from "./definitions";
export default function({ types: t }) {
@@ -9,7 +11,7 @@ export default function({ types: t }) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
const HELPER_BLACKLIST = ["interopRequireWildcard", "interopRequireDefault"];
const HEADER_HELPERS = ["interopRequireWildcard", "interopRequireDefault"];
return {
pre(file) {
@@ -23,12 +25,19 @@ export default function({ types: t }) {
? `${baseHelpersDir}/es6`
: baseHelpersDir;
file.set("helperGenerator", name => {
if (HELPER_BLACKLIST.indexOf(name) < 0) {
return this.addDefaultImport(
`${moduleName}/${helpersDir}/${name}`,
name,
);
}
const isInteropHelper = HEADER_HELPERS.indexOf(name) !== -1;
// Explicitly set the CommonJS interop helpers to their reserve
// blockHoist of 4 so they are guaranteed to exist
// when other things used them to import.
const blockHoist =
isInteropHelper && !isModule(file.path) ? 4 : undefined;
return this.addDefaultImport(
`${moduleName}/${helpersDir}/${name}`,
name,
blockHoist,
);
});
}
@@ -40,8 +49,28 @@ export default function({ types: t }) {
this.moduleName = moduleName;
this.addDefaultImport = (source, nameHint) => {
return file.addImport(source, "default", nameHint);
const cache = new Map();
this.addDefaultImport = (source, nameHint, blockHoist) => {
// If something on the page adds a helper when the file is an ES6
// file, we can't reused the cached helper name after things have been
// transformed because it has almost certainly been renamed.
const cacheKey = isModule(file.path);
const key = `${source}:${nameHint}:${cacheKey || ""}`;
let cached = cache.get(key);
if (cached) {
cached = t.cloneDeep(cached);
} else {
cached = addDefault(file.path, source, {
importedInterop: "compiled",
nameHint,
blockHoist,
});
cache.set(key, cached);
}
return cached;
};
},