Skip to content
This repository has been archived by the owner on May 11, 2018. It is now read-only.

Commit

Permalink
Add debug messaging to usage plugin (#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
existentialism authored and hzoo committed Apr 18, 2017
1 parent 28e0ce2 commit 7531362
Show file tree
Hide file tree
Showing 18 changed files with 400 additions and 83 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/lib
debug-fixtures
fixtures
/data
/flow-typed
20 changes: 20 additions & 0 deletions src/debug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import semver from "semver";
import { prettifyVersion, semverify } from "./utils";

export const logMessage = (message, context) => {
const pre = context ? `[${context}] ` : "";
const logStr = ` ${pre}${message}`;
console.log(logStr);
};

export const logPlugin = (plugin, targets, list, context) => {
const envList = list[plugin] || {};
const filteredList = Object.keys(targets).reduce((a, b) => {
if (!envList[b] || semver.lt(targets[b], semverify(envList[b]))) {
a[b] = prettifyVersion(targets[b]);
}
return a;
}, {});

logMessage(`${plugin} ${JSON.stringify(filteredList)}`, context);
};
81 changes: 33 additions & 48 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import semver from "semver";
import builtInsList from "../data/built-ins.json";
import { logPlugin } from "./debug";
import { defaultWebIncludes } from "./default-includes";
import moduleTransformations from "./module-transformations";
import normalizeOptions from "./normalize-options.js";
import pluginList from "../data/plugins.json";
import useBuiltInsEntryPlugin from "./use-built-ins-entry-plugin";
import addUsedBuiltInsPlugin from "./use-built-ins-plugin";
import getTargets from "./targets-parser";
import { prettifyTargets, prettifyVersion, semverify } from "./utils";
import { prettifyTargets, semverify } from "./utils";

/**
* Determine if a transformation is required
Expand Down Expand Up @@ -54,21 +55,6 @@ export const isPluginRequired = (supportedEnvironments, plugin) => {

let hasBeenLogged = false;

const logPlugin = (plugin, targets, list) => {
const envList = list[plugin] || {};
const filteredList = Object.keys(targets).reduce(
(a, b) => {
if (!envList[b] || semver.lt(targets[b], semverify(envList[b]))) {
a[b] = prettifyVersion(targets[b]);
}
return a;
},
{},
);
const logStr = ` ${plugin} ${JSON.stringify(filteredList)}`;
console.log(logStr);
};

const getBuiltInTargets = targets => {
const builtInTargets = Object.assign({}, targets);
if (builtInTargets.uglify != null) {
Expand Down Expand Up @@ -150,18 +136,6 @@ export default function buildPreset(context, opts = {}) {
);
}

if (debug && !hasBeenLogged) {
hasBeenLogged = true;
console.log("babel-preset-env: `DEBUG` option");
console.log("\nUsing targets:");
console.log(JSON.stringify(prettifyTargets(targets), null, 2));
console.log(`\nModules transform: ${moduleType}`);
console.log("\nUsing plugins:");
transformations.forEach(transform => {
logPlugin(transform, targets, pluginList);
});
}

const plugins = [];

if (moduleType !== false && moduleTransformations[moduleType]) {
Expand All @@ -172,38 +146,49 @@ export default function buildPreset(context, opts = {}) {
}

transformations.forEach(pluginName =>
plugins.push([require(`babel-plugin-${pluginName}`), { loose }]));
plugins.push([require(`babel-plugin-${pluginName}`), { loose }]),
);

const regenerator = transformations.has("transform-regenerator");

if (debug) {
if (debug && !hasBeenLogged) {
hasBeenLogged = true;
console.log("babel-preset-env: `DEBUG` option");
console.log("\nUsing targets:");
console.log(JSON.stringify(prettifyTargets(targets), null, 2));
console.log(`\nModules transform: ${moduleType}`);
console.log("\nUsing plugins:");
transformations.forEach(transform => {
logPlugin(transform, targets, pluginList);
});
console.log("");
console.log("Polyfills");
console.log("=========");
console.log("");

if (!useBuiltIns) {
console.log(
"None were added, since the `useBuiltIns` option was not set.",
);
}
}

if (useBuiltIns === "usage") {
plugins.push([
addUsedBuiltInsPlugin,
{
debug,
polyfills,
regenerator,
if (useBuiltIns === "usage" || useBuiltIns === "entry") {
const pluginOptions = {
debug,
polyfills,
regenerator,
onDebug: (polyfills, context) => {
polyfills.forEach(polyfill =>
logPlugin(polyfill, polyfillTargets, builtInsList, context),
);
},
]);
} else if (useBuiltIns === "entry") {
};

plugins.push([
useBuiltInsEntryPlugin,
{
debug,
polyfills,
regenerator,
onDebug: polyfill => logPlugin(polyfill, polyfillTargets, builtInsList),
},
useBuiltIns === "usage" ? addUsedBuiltInsPlugin : useBuiltInsEntryPlugin,
pluginOptions,
]);
} else if (debug) {
console.log("None were added, since the `useBuiltIns` option was not set.");
}

return {
Expand Down
8 changes: 5 additions & 3 deletions src/use-built-ins-entry-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ export default function({ types: t }) {
}

function isRequire(path) {
return t.isExpressionStatement(path.node) &&
return (
t.isExpressionStatement(path.node) &&
t.isCallExpression(path.node.expression) &&
t.isIdentifier(path.node.expression.callee) &&
path.node.expression.callee.name === "require" &&
path.node.expression.arguments.length === 1 &&
t.isStringLiteral(path.node.expression.arguments[0]) &&
isPolyfillSource(path.node.expression.arguments[0].value);
isPolyfillSource(path.node.expression.arguments[0].value)
);
}

function createImport(polyfill, requireType, core) {
Expand Down Expand Up @@ -97,7 +99,7 @@ export default function({ types: t }) {
}

console.log("Replaced `babel-polyfill` with the following polyfills:");
polyfills.forEach(polyfill => onDebug(polyfill));
onDebug(polyfills);
}
},
};
Expand Down
62 changes: 33 additions & 29 deletions src/use-built-ins-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,26 @@ function getObjectString(node) {
}
}

const modulePathMap = {
"regenerator-runtime": "babel-polyfill/lib/regenerator-runtime/runtime",
};

const getModulePath = module => {
return (
modulePathMap[module] || `babel-polyfill/lib/core-js/modules/${module}`
);
};

export default function({ types: t }) {
function addImport(path, builtIn, builtIns) {
if (builtIn && !builtIns.has(builtIn)) {
builtIns.add(builtIn);
const importDec = t.importDeclaration([], t.stringLiteral(builtIn));

const importDec = t.importDeclaration(
[],
t.stringLiteral(getModulePath(builtIn)),
);

importDec._blockHoist = 3;
const programPath = path.find(path => path.isProgram());
programPath.unshiftContainer("body", importDec);
Expand All @@ -38,28 +53,26 @@ export default function({ types: t }) {
if (Array.isArray(builtIn)) {
for (const i of builtIn) {
if (polyfills.has(i)) {
addImport(path, `babel-polyfill/lib/core-js/modules/${i}`, builtIns);
addImport(path, i, builtIns);
}
}
} else {
if (polyfills.has(builtIn)) {
addImport(
path,
`babel-polyfill/lib/core-js/modules/${builtIn}`,
builtIns,
);
addImport(path, builtIn, builtIns);
}
}
}

function isRequire(path) {
return t.isExpressionStatement(path.node) &&
return (
t.isExpressionStatement(path.node) &&
t.isCallExpression(path.node.expression) &&
t.isIdentifier(path.node.expression.callee) &&
path.node.expression.callee.name === "require" &&
path.node.expression.arguments.length === 1 &&
t.isStringLiteral(path.node.expression.arguments[0]) &&
isPolyfillSource(path.node.expression.arguments[0].value);
isPolyfillSource(path.node.expression.arguments[0].value)
);
}

const addAndRemovePolyfillImports = {
Expand Down Expand Up @@ -118,34 +131,22 @@ Please remove the "require('babel-polyfill')" call or use "useBuiltIns: 'entry'"
return;
}

addImport(
path,
"babel-polyfill/lib/core-js/modules/web.dom.iterable",
this.builtIns,
);
addImport(path, "web.dom.iterable", this.builtIns);
},

// Symbol.iterator in arr
BinaryExpression(path) {
if (path.node.operator !== "in") return;
if (!path.get("left").matchesPattern("Symbol.iterator")) return;

addImport(
path,
"babel-polyfill/lib/core-js/modules/web.dom.iterable",
this.builtIns,
);
addImport(path, "web.dom.iterable", this.builtIns);
},

// yield*
YieldExpression(path) {
if (!path.node.delegate) return;

addImport(
path,
"babel-polyfill/lib/core-js/modules/web.dom.iterable",
this.builtIns,
);
addImport(path, "web.dom.iterable", this.builtIns);
},

// Array.from
Expand Down Expand Up @@ -261,11 +262,7 @@ Please remove the "require('babel-polyfill')" call or use "useBuiltIns: 'entry'"
if (!this.usesRegenerator && (path.node.generator || path.node.async)) {
this.usesRegenerator = true;
if (state.opts.regenerator) {
addImport(
path,
"babel-polyfill/lib/regenerator-runtime/runtime",
this.builtIns,
);
addImport(path, "regenerator-runtime", this.builtIns);
}
}
},
Expand All @@ -277,6 +274,13 @@ Please remove the "require('babel-polyfill')" call or use "useBuiltIns: 'entry'"
this.builtIns = new Set();
this.usesRegenerator = false;
},
post() {
const { debug, onDebug } = this.opts;

if (debug) {
onDebug(this.builtIns, this.file.opts.filename);
}
},
visitor: addAndRemovePolyfillImports,
};
}
12 changes: 11 additions & 1 deletion test/debug-fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,21 @@ describe("debug output", () => {
);
}

const inFilesFolderLoc = path.join(testLoc, "in");

opts.inFiles = {
"src/in.js": "",
".babelrc": helper.readFile(optionsLoc),
};

if (!fs.existsSync(inFilesFolderLoc)) {
opts.inFiles["src/in.js"] = "";
} else {
fs.readdirSync(inFilesFolderLoc).forEach(filename => {
opts.inFiles[`src/${filename}`] = helper.readFile(
path.join(inFilesFolderLoc, filename),
);
});
}
it(testName, buildTest(opts));
});
});
1 change: 1 addition & 0 deletions test/debug-fixtures/usage-none/in/in.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
var foo = "bar";
5 changes: 5 additions & 0 deletions test/debug-fixtures/usage-none/in/in2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
var x = 0;

for (var i = 0; i < 5; i++) {
x += i;
}
13 changes: 13 additions & 0 deletions test/debug-fixtures/usage-none/options.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"presets": [
["../../lib", {
"debug": true,
"targets": {
"chrome": 52,
"firefox": 50,
"ie": 11
},
"useBuiltIns": "usage"
}]
]
}
40 changes: 40 additions & 0 deletions test/debug-fixtures/usage-none/stdout.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
babel-preset-env: `DEBUG` option

Using targets:
{
"chrome": "52",
"firefox": "50",
"ie": "11"
}

Modules transform: commonjs

Using plugins:
check-es2015-constants {"firefox":"50","ie":"11"}
transform-es2015-arrow-functions {"ie":"11"}
transform-es2015-block-scoping {"firefox":"50","ie":"11"}
transform-es2015-classes {"ie":"11"}
transform-es2015-computed-properties {"ie":"11"}
transform-es2015-destructuring {"firefox":"50","ie":"11"}
transform-es2015-duplicate-keys {"ie":"11"}
transform-es2015-for-of {"firefox":"50","ie":"11"}
transform-es2015-function-name {"firefox":"50","ie":"11"}
transform-es2015-literals {"firefox":"50","ie":"11"}
transform-es2015-object-super {"ie":"11"}
transform-es2015-parameters {"firefox":"50","ie":"11"}
transform-es2015-shorthand-properties {"ie":"11"}
transform-es2015-spread {"ie":"11"}
transform-es2015-sticky-regex {"ie":"11"}
transform-es2015-template-literals {"ie":"11"}
transform-es2015-typeof-symbol {"ie":"11"}
transform-es2015-unicode-regex {"ie":"11"}
transform-regenerator {"firefox":"50","ie":"11"}
transform-exponentiation-operator {"firefox":"50","ie":"11"}
transform-async-to-generator {"chrome":"52","firefox":"50","ie":"11"}
syntax-trailing-function-commas {"chrome":"52","firefox":"50","ie":"11"}

Polyfills
=========

src/in.js -> lib/in.js
src/in2.js -> lib/in2.js
3 changes: 3 additions & 0 deletions test/debug-fixtures/usage/in/in.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const foo = new Promise((resolve) => {
resolve(new Map());
});
Loading

0 comments on commit 7531362

Please sign in to comment.