diff --git a/package.json b/package.json index e62332ff1989..6f082e6cd173 100644 --- a/package.json +++ b/package.json @@ -26,8 +26,7 @@ "codecov": "^1.0.1", "derequire": "^2.0.2", "eslint": "^3.9.0", - "eslint-config-babel": "^2.0.1", - "eslint-plugin-babel": "^3.3.0", + "eslint-config-babel": "^5.0.0", "eslint-plugin-flowtype": "^2.20.0", "flow-bin": "^0.34.0", "gulp": "^3.9.0", diff --git a/packages/babel-cli/src/_babel-node.js b/packages/babel-cli/src/_babel-node.js index 3c7c40ed4d80..40471639bd9d 100644 --- a/packages/babel-cli/src/_babel-node.js +++ b/packages/babel-cli/src/_babel-node.js @@ -11,7 +11,7 @@ import _ from "lodash"; import "babel-polyfill"; import register from "babel-register"; -let program = new commander.Command("babel-node"); +const program = new commander.Command("babel-node"); program.option("-e, --eval [script]", "Evaluate script"); program.option("-p, --print [code]", "Evaluate script and print result"); @@ -21,7 +21,7 @@ program.option("-x, --extensions [extensions]", "List of extensions to hook into program.option("-w, --plugins [string]", "", util.list); program.option("-b, --presets [string]", "", util.list); -let pkg = require("../package.json"); +const pkg = require("../package.json"); program.version(pkg.version); program.usage("[options] [ -e script | script.js ] [arguments]"); program.parse(process.argv); @@ -38,7 +38,7 @@ register({ // -let replPlugin = ({ types: t }) => ({ +const replPlugin = ({ types: t }) => ({ visitor: { ModuleDeclaration(path) { throw path.buildCodeFrameError("Modules aren't supported in the REPL"); @@ -62,7 +62,7 @@ let replPlugin = ({ types: t }) => ({ // -let _eval = function (code, filename) { +const _eval = function (code, filename) { code = code.trim(); if (!code) return undefined; @@ -84,7 +84,7 @@ if (program.eval || program.print) { global.__filename = "[eval]"; global.__dirname = process.cwd(); - let module = new Module(global.__filename); + const module = new Module(global.__filename); module.filename = global.__filename; module.paths = Module._nodeModulePaths(global.__dirname); @@ -92,9 +92,9 @@ if (program.eval || program.print) { global.module = module; global.require = module.require.bind(module); - let result = _eval(code, global.__filename); + const result = _eval(code, global.__filename); if (program.print) { - let output = _.isString(result) ? result : inspect(result); + const output = _.isString(result) ? result : inspect(result); process.stdout.write(output + "\n"); } } else { @@ -111,7 +111,7 @@ if (program.eval || program.print) { } if (arg[0] === "-") { - let parsedArg = program[arg.slice(2)]; + const parsedArg = program[arg.slice(2)]; if (parsedArg && parsedArg !== true) { ignoreNext = true; } @@ -123,7 +123,7 @@ if (program.eval || program.print) { args = args.slice(i); // make the filename absolute - let filename = args[0]; + const filename = args[0]; if (!pathIsAbsolute(filename)) args[0] = path.join(process.cwd(), filename); // add back on node and concat the sliced args diff --git a/packages/babel-cli/src/babel-node.js b/packages/babel-cli/src/babel-node.js index 0830a2313d43..e3d0c2e90196 100755 --- a/packages/babel-cli/src/babel-node.js +++ b/packages/babel-cli/src/babel-node.js @@ -5,8 +5,8 @@ * when found, before invoking the "real" _babel-node(1) executable. */ -let getV8Flags = require("v8flags"); -let path = require("path"); +const getV8Flags = require("v8flags"); +const path = require("path"); let args = [path.join(__dirname, "_babel-node")]; @@ -14,7 +14,7 @@ let babelArgs = process.argv.slice(2); let userArgs; // separate node arguments from script arguments -let argSeparator = babelArgs.indexOf("--"); +const argSeparator = babelArgs.indexOf("--"); if (argSeparator > -1) { userArgs = babelArgs.slice(argSeparator); // including the -- babelArgs = babelArgs.slice(0, argSeparator); @@ -75,13 +75,13 @@ getV8Flags(function (err, v8Flags) { } try { - let kexec = require("kexec"); + const kexec = require("kexec"); kexec(process.argv[0], args); } catch (err) { if (err.code !== "MODULE_NOT_FOUND") throw err; - let child_process = require("child_process"); - let proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" }); + const child_process = require("child_process"); + const proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" }); proc.on("exit", function (code, signal) { process.on("exit", function () { if (signal) { diff --git a/packages/babel-cli/src/babel/dir.js b/packages/babel-cli/src/babel/dir.js index 78be975c8885..f097874a2a0e 100644 --- a/packages/babel-cli/src/babel/dir.js +++ b/packages/babel-cli/src/babel/dir.js @@ -1,18 +1,18 @@ -let outputFileSync = require("output-file-sync"); -let slash = require("slash"); -let path = require("path"); -let util = require("./util"); -let fs = require("fs"); -let _ = require("lodash"); +const outputFileSync = require("output-file-sync"); +const slash = require("slash"); +const path = require("path"); +const util = require("./util"); +const fs = require("fs"); +const _ = require("lodash"); module.exports = function (commander, filenames) { function write(src, relative) { // remove extension and then append back on .js relative = relative.replace(/\.(\w*?)$/, "") + ".js"; - let dest = path.join(commander.outDir, relative); + const dest = path.join(commander.outDir, relative); - let data = util.compile(src, { + const data = util.compile(src, { sourceFileName: slash(path.relative(dest + "/..", src)), sourceMapTarget: path.basename(relative) }); @@ -20,7 +20,7 @@ module.exports = function (commander, filenames) { // we've requested explicit sourcemaps to be written to disk if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") { - let mapLoc = dest + ".map"; + const mapLoc = dest + ".map"; data.code = util.addSourceMappingUrl(data.code, mapLoc); outputFileSync(mapLoc, JSON.stringify(data.map)); } @@ -37,7 +37,7 @@ module.exports = function (commander, filenames) { if (util.canCompile(filename, commander.extensions)) { write(src, filename); } else if (commander.copyFiles) { - let dest = path.join(commander.outDir, filename); + const dest = path.join(commander.outDir, filename); outputFileSync(dest, fs.readFileSync(src)); util.chmod(src, dest); } @@ -46,13 +46,13 @@ module.exports = function (commander, filenames) { function handle(filename) { if (!fs.existsSync(filename)) return; - let stat = fs.statSync(filename); + const stat = fs.statSync(filename); if (stat.isDirectory(filename)) { - let dirname = filename; + const dirname = filename; _.each(util.readdir(dirname), function (filename) { - let src = path.join(dirname, filename); + const src = path.join(dirname, filename); handleFile(src, filename); }); } else { @@ -65,17 +65,17 @@ module.exports = function (commander, filenames) { } if (commander.watch) { - let chokidar = util.requireChokidar(); + const chokidar = util.requireChokidar(); _.each(filenames, function (dirname) { - let watcher = chokidar.watch(dirname, { + const watcher = chokidar.watch(dirname, { persistent: true, ignoreInitial: true }); _.each(["add", "change"], function (type) { watcher.on(type, function (filename) { - let relative = path.relative(dirname, filename) || filename; + const relative = path.relative(dirname, filename) || filename; try { handleFile(filename, relative); } catch (err) { diff --git a/packages/babel-cli/src/babel/file.js b/packages/babel-cli/src/babel/file.js index 1feb8d2aadc3..bb1f6e949486 100644 --- a/packages/babel-cli/src/babel/file.js +++ b/packages/babel-cli/src/babel/file.js @@ -1,10 +1,10 @@ -let convertSourceMap = require("convert-source-map"); -let sourceMap = require("source-map"); -let slash = require("slash"); -let path = require("path"); -let util = require("./util"); -let fs = require("fs"); -let _ = require("lodash"); +const convertSourceMap = require("convert-source-map"); +const sourceMap = require("source-map"); +const slash = require("slash"); +const path = require("path"); +const util = require("./util"); +const fs = require("fs"); +const _ = require("lodash"); module.exports = function (commander, filenames, opts) { if (commander.sourceMaps === "inline") { @@ -13,8 +13,8 @@ module.exports = function (commander, filenames, opts) { let results = []; - let buildResult = function () { - let map = new sourceMap.SourceMapGenerator({ + const buildResult = function () { + const map = new sourceMap.SourceMapGenerator({ file: path.basename(commander.outFile || "") || "stdout", sourceRoot: opts.sourceRoot }); @@ -26,8 +26,8 @@ module.exports = function (commander, filenames, opts) { code += result.code + "\n"; if (result.map) { - let consumer = new sourceMap.SourceMapConsumer(result.map); - let sources = new Set(); + const consumer = new sourceMap.SourceMapConsumer(result.map); + const sources = new Set(); consumer.eachMapping(function (mapping) { if (mapping.source != null) sources.add(mapping.source); @@ -46,7 +46,7 @@ module.exports = function (commander, filenames, opts) { }); sources.forEach((source) => { - let content = consumer.sourceContentFor(source, true); + const content = consumer.sourceContentFor(source, true); if (content !== null) { map.setSourceContent(source, content); } @@ -68,13 +68,13 @@ module.exports = function (commander, filenames, opts) { }; }; - let output = function () { - let result = buildResult(); + const output = function () { + const result = buildResult(); if (commander.outFile) { // we've requested for a sourcemap to be written to disk if (commander.sourceMaps && commander.sourceMaps !== "inline") { - let mapLoc = commander.outFile + ".map"; + const mapLoc = commander.outFile + ".map"; result.code = util.addSourceMappingUrl(result.code, mapLoc); fs.writeFileSync(mapLoc, JSON.stringify(result.map)); } @@ -85,13 +85,13 @@ module.exports = function (commander, filenames, opts) { } }; - let stdin = function () { + const stdin = function () { let code = ""; process.stdin.setEncoding("utf8"); process.stdin.on("readable", function () { - let chunk = process.stdin.read(); + const chunk = process.stdin.read(); if (chunk !== null) code += chunk; }); @@ -103,16 +103,16 @@ module.exports = function (commander, filenames, opts) { }); }; - let walk = function () { - let _filenames = []; + const walk = function () { + const _filenames = []; results = []; _.each(filenames, function (filename) { if (!fs.existsSync(filename)) return; - let stat = fs.statSync(filename); + const stat = fs.statSync(filename); if (stat.isDirectory()) { - let dirname = filename; + const dirname = filename; _.each(util.readdirFilter(filename), function (filename) { _filenames.push(path.join(dirname, filename)); @@ -131,7 +131,7 @@ module.exports = function (commander, filenames, opts) { } sourceFilename = slash(sourceFilename); - let data = util.compile(filename, { + const data = util.compile(filename, { sourceFileName: sourceFilename, }); @@ -142,14 +142,14 @@ module.exports = function (commander, filenames, opts) { output(); }; - let files = function () { + const files = function () { if (!commander.skipInitialBuild) { walk(); } if (commander.watch) { - let chokidar = util.requireChokidar(); + const chokidar = util.requireChokidar(); chokidar.watch(filenames, { persistent: true, ignoreInitial: true diff --git a/packages/babel-cli/src/babel/index.js b/packages/babel-cli/src/babel/index.js index 236c2df72aae..0e1472d953a3 100755 --- a/packages/babel-cli/src/babel/index.js +++ b/packages/babel-cli/src/babel/index.js @@ -3,14 +3,14 @@ require("babel-core"); -let fs = require("fs"); -let commander = require("commander"); -let kebabCase = require("lodash/kebabCase"); -let options = require("babel-core").options; -let util = require("babel-core").util; -let uniq = require("lodash/uniq"); -let each = require("lodash/each"); -let glob = require("glob"); +const fs = require("fs"); +const commander = require("commander"); +const kebabCase = require("lodash/kebabCase"); +const options = require("babel-core").options; +const util = require("babel-core").util; +const uniq = require("lodash/uniq"); +const each = require("lodash/each"); +const glob = require("glob"); each(options, function (option, key) { if (option.hidden) return; @@ -31,7 +31,7 @@ each(options, function (option, key) { arg = "-" + option.shorthand + ", " + arg; } - let desc = []; + const desc = []; if (option.deprecated) desc.push("[DEPRECATED] " + option.deprecated); if (option.description) desc.push(option.description); @@ -46,7 +46,7 @@ commander.option("-d, --out-dir [out]", "Compile an input directory of modules i commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files"); commander.option("-q, --quiet", "Don't log anything"); -let pkg = require("../../package.json"); +const pkg = require("../../package.json"); commander.version(pkg.version + " (babel-core " + require("babel-core").version + ")"); commander.usage("[options] "); commander.parse(process.argv); @@ -59,7 +59,7 @@ if (commander.extensions) { // -let errors = []; +const errors = []; let filenames = commander.args.reduce(function (globbed, input) { let files = glob.sync(input); @@ -104,7 +104,7 @@ if (errors.length) { // -let opts = exports.opts = {}; +const opts = exports.opts = {}; each(options, function (opt, key) { if (commander[key] !== undefined && commander[key] !== opt.default) { diff --git a/packages/babel-cli/src/babel/util.js b/packages/babel-cli/src/babel/util.js index fd06aa6ce78c..df8c72b3aa9e 100644 --- a/packages/babel-cli/src/babel/util.js +++ b/packages/babel-cli/src/babel/util.js @@ -1,11 +1,11 @@ -let commander = require("commander"); -let readdir = require("fs-readdir-recursive"); -let index = require("./index"); -let babel = require("babel-core"); -let util = require("babel-core").util; -let path = require("path"); -let fs = require("fs"); -let _ = require("lodash"); +const commander = require("commander"); +const readdir = require("fs-readdir-recursive"); +const index = require("./index"); +const babel = require("babel-core"); +const util = require("babel-core").util; +const path = require("path"); +const fs = require("fs"); +const _ = require("lodash"); export function chmod(src, dest) { fs.chmodSync(dest, fs.statSync(src).mode); @@ -19,7 +19,7 @@ export function readdirFilter(filename) { export { readdir }; -export let canCompile = util.canCompile; +export const canCompile = util.canCompile; export function shouldIgnore(loc) { return util.shouldIgnore(loc, index.opts.ignore, index.opts.only); @@ -37,7 +37,7 @@ export function transform(filename, code, opts) { opts = _.defaults(opts || {}, index.opts); opts.filename = filename; - let result = babel.transform(code, opts); + const result = babel.transform(code, opts); result.filename = filename; result.actual = code; return result; @@ -45,7 +45,7 @@ export function transform(filename, code, opts) { export function compile(filename, opts) { try { - let code = fs.readFileSync(filename, "utf8"); + const code = fs.readFileSync(filename, "utf8"); return transform(filename, code, opts); } catch (err) { if (commander.watch) { diff --git a/packages/babel-cli/test/index.js b/packages/babel-cli/test/index.js index 61cb19aed949..9a5d9f0594a6 100644 --- a/packages/babel-cli/test/index.js +++ b/packages/babel-cli/test/index.js @@ -1,29 +1,29 @@ -let readdir = require("fs-readdir-recursive"); -let helper = require("babel-helper-fixtures"); -let assert = require("assert"); -let rimraf = require("rimraf"); -let outputFileSync = require("output-file-sync"); -let child = require("child_process"); -let path = require("path"); -let chai = require("chai"); -let fs = require("fs"); -let _ = require("lodash"); - -let fixtureLoc = path.join(__dirname, "fixtures"); -let tmpLoc = path.join(__dirname, "tmp"); - -let presetLocs = [ +const readdir = require("fs-readdir-recursive"); +const helper = require("babel-helper-fixtures"); +const assert = require("assert"); +const rimraf = require("rimraf"); +const outputFileSync = require("output-file-sync"); +const child = require("child_process"); +const path = require("path"); +const chai = require("chai"); +const fs = require("fs"); +const _ = require("lodash"); + +const fixtureLoc = path.join(__dirname, "fixtures"); +const tmpLoc = path.join(__dirname, "tmp"); + +const presetLocs = [ path.join(__dirname, "../../babel-preset-es2015"), path.join(__dirname, "../../babel-preset-react") ].join(","); -let pluginLocs = [ +const pluginLocs = [ path.join(__dirname, "/../../babel-plugin-transform-strict-mode"), path.join(__dirname, "/../../babel-plugin-transform-es2015-modules-commonjs"), ].join(","); -let readDir = function (loc) { - let files = {}; +const readDir = function (loc) { + const files = {}; if (fs.existsSync(loc)) { _.each(readdir(loc), function (filename) { files[filename] = helper.readFile(path.join(loc, filename)); @@ -32,14 +32,14 @@ let readDir = function (loc) { return files; }; -let saveInFiles = function (files) { +const saveInFiles = function (files) { _.each(files, function (content, filename) { outputFileSync(filename, content); }); }; -let assertTest = function (stdout, stderr, opts) { - let expectStderr = opts.stderr.trim(); +const assertTest = function (stdout, stderr, opts) { + const expectStderr = opts.stderr.trim(); stderr = stderr.trim(); if (opts.stderr) { @@ -52,7 +52,7 @@ let assertTest = function (stdout, stderr, opts) { throw new Error("stderr:\n" + stderr); } - let expectStdout = opts.stdout.trim(); + const expectStdout = opts.stdout.trim(); stdout = stdout.trim(); stdout = stdout.replace(/\\/g, "/"); @@ -67,13 +67,13 @@ let assertTest = function (stdout, stderr, opts) { } _.each(opts.outFiles, function (expect, filename) { - let actual = helper.readFile(filename); + const actual = helper.readFile(filename); chai.expect(actual).to.equal(expect, "out-file " + filename); }); }; -let buildTest = function (binName, testName, opts) { - let binLoc = path.join(__dirname, "../lib", binName); +const buildTest = function (binName, testName, opts) { + const binLoc = path.join(__dirname, "../lib", binName); return function (callback) { clear(); @@ -91,7 +91,7 @@ let buildTest = function (binName, testName, opts) { args = args.concat(opts.args); - let spawn = child.spawn(process.execPath, args); + const spawn = child.spawn(process.execPath, args); let stderr = ""; let stdout = ""; @@ -127,7 +127,7 @@ let buildTest = function (binName, testName, opts) { }; }; -let clear = function () { +const clear = function () { process.chdir(__dirname); if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc); fs.mkdirSync(tmpLoc); @@ -137,22 +137,22 @@ let clear = function () { _.each(fs.readdirSync(fixtureLoc), function (binName) { if (binName[0] === ".") return; - let suiteLoc = path.join(fixtureLoc, binName); + const suiteLoc = path.join(fixtureLoc, binName); describe("bin/" + binName, function () { _.each(fs.readdirSync(suiteLoc), function (testName) { if (testName[0] === ".") return; - let testLoc = path.join(suiteLoc, testName); + const testLoc = path.join(suiteLoc, testName); - let opts = { + const opts = { args: [] }; - let optionsLoc = path.join(testLoc, "options.json"); + const optionsLoc = path.join(testLoc, "options.json"); if (fs.existsSync(optionsLoc)) _.merge(opts, require(optionsLoc)); _.each(["stdout", "stdin", "stderr"], function (key) { - let loc = path.join(testLoc, key + ".txt"); + const loc = path.join(testLoc, key + ".txt"); if (fs.existsSync(loc)) { opts[key] = helper.readFile(loc); } else { @@ -163,7 +163,7 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) { opts.outFiles = readDir(path.join(testLoc, "out-files")); opts.inFiles = readDir(path.join(testLoc, "in-files")); - let babelrcLoc = path.join(testLoc, ".babelrc"); + const babelrcLoc = path.join(testLoc, ".babelrc"); if (fs.existsSync(babelrcLoc)) { // copy .babelrc file to tmp directory opts.inFiles[".babelrc"] = helper.readFile(babelrcLoc); diff --git a/packages/babel-code-frame/src/index.js b/packages/babel-code-frame/src/index.js index 1e570ab69259..9476ef617d22 100644 --- a/packages/babel-code-frame/src/index.js +++ b/packages/babel-code-frame/src/index.js @@ -46,8 +46,8 @@ const BRACKET = /^[()\[\]{}]$/; */ function getTokenType(match) { - let [offset, text] = match.slice(-2); - let token = matchToToken(match); + const [offset, text] = match.slice(-2); + const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { @@ -79,8 +79,8 @@ function getTokenType(match) { function highlight(defs: Object, text: string) { return text.replace(jsTokens, function (...args) { - let type = getTokenType(args); - let colorize = defs[type]; + const type = getTokenType(args); + const colorize = defs[type]; if (colorize) { return args[0].split(NEWLINE).map((str) => colorize(str)).join("\n"); } else { @@ -101,21 +101,21 @@ export default function ( ): string { colNumber = Math.max(colNumber, 0); - let highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor; + const highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor; let chalk = Chalk; if (opts.forceColor) { chalk = new Chalk.constructor({ enabled: true }); } - let maybeHighlight = (chalkFn, string) => { + const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; - let defs = getDefs(chalk); + const defs = getDefs(chalk); if (highlighted) rawLines = highlight(defs, rawLines); - let linesAbove = opts.linesAbove || 2; - let linesBelow = opts.linesBelow || 3; + const linesAbove = opts.linesAbove || 2; + const linesBelow = opts.linesBelow || 3; - let lines = rawLines.split(NEWLINE); + const lines = rawLines.split(NEWLINE); let start = Math.max(lineNumber - (linesAbove + 1), 0); let end = Math.min(lines.length, lineNumber + linesBelow); @@ -124,16 +124,16 @@ export default function ( end = lines.length; } - let numberMaxWidth = String(end).length; + const numberMaxWidth = String(end).length; - let frame = lines.slice(start, end).map((line, index) => { - let number = start + 1 + index; - let paddedNumber = ` ${number}`.slice(-numberMaxWidth); - let gutter = ` ${paddedNumber} | `; + const frame = lines.slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} | `; if (number === lineNumber) { let markerLine = ""; if (colNumber) { - let markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); + const markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); markerLine = [ "\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), diff --git a/packages/babel-code-frame/test/index.js b/packages/babel-code-frame/test/index.js index c85d59ddec60..b00b88386db4 100644 --- a/packages/babel-code-frame/test/index.js +++ b/packages/babel-code-frame/test/index.js @@ -1,6 +1,6 @@ -let assert = require("assert"); -let chalk = require("chalk"); -let codeFrame = require(".."); +const assert = require("assert"); +const chalk = require("chalk"); +const codeFrame = require(".."); describe("babel-code-frame", function () { it("basic usage", function () { @@ -119,7 +119,7 @@ describe("babel-code-frame", function () { }); it("opts.linesAbove", function () { - let rawLines = [ + const rawLines = [ "/**", " * Sums two numbers.", " *", @@ -143,7 +143,7 @@ describe("babel-code-frame", function () { }); it("opts.linesBelow", function () { - let rawLines = [ + const rawLines = [ "/**", " * Sums two numbers.", " *", @@ -166,7 +166,7 @@ describe("babel-code-frame", function () { }); it("opts.linesAbove and opts.linesBelow", function () { - let rawLines = [ + const rawLines = [ "/**", " * Sums two numbers.", " *", @@ -188,10 +188,10 @@ describe("babel-code-frame", function () { }); it("opts.forceColor", function() { - let marker = chalk.red.bold; - let gutter = chalk.grey; + const marker = chalk.red.bold; + const gutter = chalk.grey; - let rawLines = [ + const rawLines = [ "", "", "", diff --git a/packages/babel-core/src/api/browser.js b/packages/babel-core/src/api/browser.js index 1c53951acf38..d5d89f6b71d9 100644 --- a/packages/babel-core/src/api/browser.js +++ b/packages/babel-core/src/api/browser.js @@ -29,16 +29,16 @@ export function run(code: string, opts: Object = {}): any { export function load(url: string, callback: Function, opts: Object = {}, hold?: boolean) { opts.filename = opts.filename || url; - let xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest(); + const xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest(); xhr.open("GET", url, true); if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain"); xhr.onreadystatechange = function () { if (xhr.readyState !== 4) return; - let status = xhr.status; + const status = xhr.status; if (status === 0 || status === 200) { - let param = [xhr.responseText, opts]; + const param = [xhr.responseText, opts]; if (!hold) run(param); if (callback) callback(param); } else { @@ -50,8 +50,8 @@ export function load(url: string, callback: Function, opts: Object = {}, hold?: } function runScripts() { - let scripts: Array | Object> = []; - let types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; + const scripts: Array | Object> = []; + const types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; let index = 0; /** @@ -59,7 +59,7 @@ function runScripts() { */ function exec() { - let param = scripts[index]; + const param = scripts[index]; if (param instanceof Array) { run(param, index); index++; @@ -72,7 +72,7 @@ function runScripts() { */ function run(script: Object, i: number) { - let opts = {}; + const opts = {}; if (script.src) { load(script.src, function (param) { @@ -87,10 +87,10 @@ function runScripts() { // Collect scripts with Babel `types`. - let _scripts = global.document.getElementsByTagName("script"); + const _scripts = global.document.getElementsByTagName("script"); for (let i = 0; i < _scripts.length; ++i) { - let _script = _scripts[i]; + const _script = _scripts[i]; if (types.indexOf(_script.type) >= 0) scripts.push(_script); } diff --git a/packages/babel-core/src/api/node.js b/packages/babel-core/src/api/node.js index a9e4792465d3..de1cfea682cc 100644 --- a/packages/babel-core/src/api/node.js +++ b/packages/babel-core/src/api/node.js @@ -31,10 +31,10 @@ export function Plugin(alias) { import Pipeline from "../transformation/pipeline"; export { Pipeline }; -let pipeline = new Pipeline; -export let analyse = pipeline.analyse.bind(pipeline); -export let transform = pipeline.transform.bind(pipeline); -export let transformFromAst = pipeline.transformFromAst.bind(pipeline); +const pipeline = new Pipeline; +export const analyse = pipeline.analyse.bind(pipeline); +export const transform = pipeline.transform.bind(pipeline); +export const transformFromAst = pipeline.transformFromAst.bind(pipeline); export function transformFile(filename: string, opts?: Object, callback: Function) { if (isFunction(opts)) { diff --git a/packages/babel-core/src/helpers/get-possible-preset-names.js b/packages/babel-core/src/helpers/get-possible-preset-names.js index b9fb1726bd06..a2140b9887fa 100644 --- a/packages/babel-core/src/helpers/get-possible-preset-names.js +++ b/packages/babel-core/src/helpers/get-possible-preset-names.js @@ -1,11 +1,11 @@ export default function getPossiblePresetNames(presetName: string): Array { - let possibleNames = [`babel-preset-${presetName}`, presetName]; + const possibleNames = [`babel-preset-${presetName}`, presetName]; // trying to resolve @organization shortcat // @foo/es2015 -> @foo/babel-preset-es2015 - let matches = presetName.match(/^(@[^/]+)\/(.+)$/); + const matches = presetName.match(/^(@[^/]+)\/(.+)$/); if (matches) { - let [, orgName, presetPath] = matches; + const [, orgName, presetPath] = matches; possibleNames.push(`${orgName}/babel-preset-${presetPath}`); } diff --git a/packages/babel-core/src/helpers/merge.js b/packages/babel-core/src/helpers/merge.js index 5a695f6afa1d..1a01e22889c7 100644 --- a/packages/babel-core/src/helpers/merge.js +++ b/packages/babel-core/src/helpers/merge.js @@ -5,9 +5,9 @@ export default function (dest?: Object, src?: Object): ?Object { return mergeWith(dest, src, function (a, b) { if (b && Array.isArray(a)) { - let newArray = b.slice(0); + const newArray = b.slice(0); - for (let item of a) { + for (const item of a) { if (newArray.indexOf(item) < 0) { newArray.push(item); } diff --git a/packages/babel-core/src/helpers/resolve.js b/packages/babel-core/src/helpers/resolve.js index 623a910cbf38..e8493ac8f599 100644 --- a/packages/babel-core/src/helpers/resolve.js +++ b/packages/babel-core/src/helpers/resolve.js @@ -1,7 +1,7 @@ import Module from "module"; import path from "path"; -let relativeModules = {}; +const relativeModules = {}; export default function (loc: string, relative: string = process.cwd()): ?string { // we're in the browser, probably @@ -18,7 +18,7 @@ export default function (loc: string, relative: string = process.cwd()): ?string // Node presumes "." is process.cwd(), not our relative path. // Since this fake module is never "loaded", we don't have to worry about mutating // any global Node module cache state here. - let filename = path.join(relative, ".babelrc"); + const filename = path.join(relative, ".babelrc"); relativeMod.id = filename; relativeMod.filename = filename; diff --git a/packages/babel-core/src/store.js b/packages/babel-core/src/store.js index fab3d10f341d..1b172efbe045 100644 --- a/packages/babel-core/src/store.js +++ b/packages/babel-core/src/store.js @@ -15,7 +15,7 @@ export default class Store extends Map { return super.get(key); } else { if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { - let val = this.dynamicData[key](); + const val = this.dynamicData[key](); this.set(key, val); return val; } diff --git a/packages/babel-core/src/tools/build-external-helpers.js b/packages/babel-core/src/tools/build-external-helpers.js index a26febd34bbe..237daf532c49 100644 --- a/packages/babel-core/src/tools/build-external-helpers.js +++ b/packages/babel-core/src/tools/build-external-helpers.js @@ -7,7 +7,7 @@ import template from "babel-template"; import each from "lodash/each"; import * as t from "babel-types"; -let buildUmdWrapper = template(` +const buildUmdWrapper = template(` (function (root, factory) { if (typeof define === "function" && define.amd) { define(AMD_ARGUMENTS, factory); @@ -22,9 +22,9 @@ let buildUmdWrapper = template(` `); function buildGlobal(namespace, builder) { - let body = []; - let container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); - let tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); + const body = []; + const container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); + const tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); body.push(t.variableDeclaration("var", [ t.variableDeclarator( @@ -39,7 +39,7 @@ function buildGlobal(namespace, builder) { } function buildUmd(namespace, builder) { - let body = []; + const body = []; body.push(t.variableDeclaration("var", [ t.variableDeclarator(namespace, t.identifier("global")) ])); @@ -63,7 +63,7 @@ function buildUmd(namespace, builder) { } function buildVar(namespace, builder) { - let body = []; + const body = []; body.push(t.variableDeclaration("var", [ t.variableDeclarator(namespace, t.objectExpression([])) ])); @@ -76,7 +76,7 @@ function buildHelpers(body, namespace, whitelist) { each(helpers.list, function (name) { if (whitelist && whitelist.indexOf(name) < 0) return; - let key = t.identifier(name); + const key = t.identifier(name); body.push(t.expressionStatement( t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)) )); @@ -86,15 +86,15 @@ export default function ( whitelist?: Array, outputType: "global" | "umd" | "var" = "global", ) { - let namespace = t.identifier("babelHelpers"); + const namespace = t.identifier("babelHelpers"); - let builder = function (body) { + const builder = function (body) { return buildHelpers(body, namespace, whitelist); }; let tree; - let build = { + const build = { global: buildGlobal, umd: buildUmd, var: buildVar, diff --git a/packages/babel-core/src/transformation/file/index.js b/packages/babel-core/src/transformation/file/index.js index 01d5b7efc9d3..a013eb5d6a43 100644 --- a/packages/babel-core/src/transformation/file/index.js +++ b/packages/babel-core/src/transformation/file/index.js @@ -32,9 +32,9 @@ const INTERNAL_PLUGINS = [ [shadowFunctionsPlugin] ]; -let errorVisitor = { +const errorVisitor = { enter(path, state) { - let loc = path.node.loc; + const loc = path.node.loc; if (loc) { state.loc = loc; path.stop(); @@ -69,7 +69,7 @@ export default class File extends Store { // All the "per preset" options are inherited from the main options. this.perPresetOpts = []; this.opts.presets.forEach((presetOpts) => { - let perPresetOpts = Object.assign(Object.create(this.opts), presetOpts); + const perPresetOpts = Object.assign(Object.create(this.opts), presetOpts); this.perPresetOpts.push(perPresetOpts); this.buildPluginsForOptions(perPresetOpts); }); @@ -125,7 +125,7 @@ export default class File extends Store { getMetadata() { let has = false; - for (let node of (this.ast.program.body: Array)) { + for (const node of (this.ast.program.body: Array)) { if (t.isModuleDeclaration(node)) { has = true; break; @@ -165,7 +165,7 @@ export default class File extends Store { filenameRelative: opts.filename }); - let basenameRelative = path.basename(opts.filenameRelative); + const basenameRelative = path.basename(opts.filenameRelative); defaults(opts, { sourceFileName: basenameRelative, @@ -180,13 +180,13 @@ export default class File extends Store { return; } - let plugins: Array<[PluginPass, Object]> = opts.plugins.concat(INTERNAL_PLUGINS); - let currentPluginVisitors = []; - let currentPluginPasses = []; + const plugins: Array<[PluginPass, Object]> = opts.plugins.concat(INTERNAL_PLUGINS); + const currentPluginVisitors = []; + const currentPluginPasses = []; // init plugins! - for (let ref of plugins) { - let [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug + for (const ref of plugins) { + const [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug currentPluginVisitors.push(plugin.visitor); currentPluginPasses.push(new PluginPass(this, plugin, pluginOpts)); @@ -201,7 +201,7 @@ export default class File extends Store { } getModuleName(): ?string { - let opts = this.opts; + const opts = this.opts; if (!opts.moduleIds) { return null; } @@ -224,7 +224,7 @@ export default class File extends Store { if (opts.sourceRoot != null) { // remove sourceRoot from filename - let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); + const sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); } @@ -245,20 +245,20 @@ export default class File extends Store { } resolveModuleSource(source: string): string { - let resolveModuleSource = this.opts.resolveModuleSource; + const resolveModuleSource = this.opts.resolveModuleSource; if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); return source; } addImport(source: string, imported: string, name?: string = imported): Object { - let alias = `${source}:${imported}`; + const alias = `${source}:${imported}`; let id = this.dynamicImportIds[alias]; if (!id) { source = this.resolveModuleSource(source); id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); - let specifiers = []; + const specifiers = []; if (imported === "*") { specifiers.push(t.importNamespaceSpecifier(id)); @@ -268,7 +268,7 @@ export default class File extends Store { specifiers.push(t.importSpecifier(id, t.identifier(imported))); } - let declar = t.importDeclaration(specifiers, t.stringLiteral(source)); + const declar = t.importDeclaration(specifiers, t.stringLiteral(source)); declar._blockHoist = 3; this.path.unshiftContainer("body", declar); @@ -278,7 +278,7 @@ export default class File extends Store { } addHelper(name: string): Object { - let declar = this.declarations[name]; + const declar = this.declarations[name]; if (declar) return declar; if (!this.usedHelpers[name]) { @@ -286,17 +286,17 @@ export default class File extends Store { this.usedHelpers[name] = true; } - let generator = this.get("helperGenerator"); - let runtime = this.get("helpersNamespace"); + const generator = this.get("helperGenerator"); + const runtime = this.get("helpersNamespace"); if (generator) { - let res = generator(name); + const res = generator(name); if (res) return res; } else if (runtime) { return t.memberExpression(runtime, t.identifier(name)); } - let ref = getHelper(name); - let uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + const ref = getHelper(name); + const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); if (t.isFunctionExpression(ref) && !ref.id) { ref.body._compact = true; @@ -323,18 +323,18 @@ export default class File extends Store { ): Object { // Generate a unique name based on the string literals so we dedupe // identical strings used in the program. - let stringIds = raw.elements.map(function(string) { + const stringIds = raw.elements.map(function(string) { return string.value; }); - let name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`; + const name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`; - let declar = this.declarations[name]; + const declar = this.declarations[name]; if (declar) return declar; - let uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); + const uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); - let helperId = this.addHelper(helperName); - let init = t.callExpression(helperId, [strings, raw]); + const helperId = this.addHelper(helperName); + const init = t.callExpression(helperId, [strings, raw]); init._compact = true; this.scope.push({ id: uid, @@ -345,9 +345,9 @@ export default class File extends Store { } buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error { - let loc = node && (node.loc || node._loc); + const loc = node && (node.loc || node._loc); - let err = new Error(msg); + const err = new Error(msg); if (loc) { err.loc = loc.start; @@ -367,13 +367,13 @@ export default class File extends Store { } mergeSourceMap(map: Object) { - let inputMap = this.opts.inputSourceMap; + const inputMap = this.opts.inputSourceMap; if (inputMap) { - let inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap); - let outputMapConsumer = new sourceMap.SourceMapConsumer(map); + const inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap); + const outputMapConsumer = new sourceMap.SourceMapConsumer(map); - let mergedGenerator = new sourceMap.SourceMapGenerator({ + const mergedGenerator = new sourceMap.SourceMapGenerator({ file: inputMapConsumer.file, sourceRoot: inputMapConsumer.sourceRoot }); @@ -402,7 +402,7 @@ export default class File extends Store { } }); - let mergedMap = mergedGenerator.toJSON(); + const mergedMap = mergedGenerator.toJSON(); inputMap.mappings = mergedMap.mappings; return inputMap; } else { @@ -419,8 +419,8 @@ export default class File extends Store { if (parserOpts.parser) { if (typeof parserOpts.parser === "string") { - let dirname = path.dirname(this.opts.filename) || process.cwd(); - let parser = resolve(parserOpts.parser, dirname); + const dirname = path.dirname(this.opts.filename) || process.cwd(); + const parser = resolve(parserOpts.parser, dirname); if (parser) { parseCode = require(parser).parse; } else { @@ -439,7 +439,7 @@ export default class File extends Store { } this.log.debug("Parse start"); - let ast = parseCode(code, parserOpts || this.parserOpts); + const ast = parseCode(code, parserOpts || this.parserOpts); this.log.debug("Parse stop"); return ast; } @@ -472,7 +472,7 @@ export default class File extends Store { this.log.debug("Start transform traverse"); // merge all plugin visitors into a single visitor - let visitor = traverse.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); + const visitor = traverse.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); traverse(this.ast, visitor, this.scope); this.log.debug("End transform traverse"); @@ -500,7 +500,7 @@ export default class File extends Store { let message = err.message = `${this.opts.filename}: ${err.message}`; - let loc = err.loc; + const loc = err.loc; if (loc) { err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts); message += "\n" + err.codeFrame; @@ -513,7 +513,7 @@ export default class File extends Store { } if (err.stack) { - let newStack = err.stack.replace(err.message, message); + const newStack = err.stack.replace(err.message, message); err.stack = newStack; } @@ -529,28 +529,28 @@ export default class File extends Store { parseCode() { this.parseShebang(); - let ast = this.parse(this.code); + const ast = this.parse(this.code); this.addAst(ast); } shouldIgnore() { - let opts = this.opts; + const opts = this.opts; return util.shouldIgnore(opts.filename, opts.ignore, opts.only); } call(key: "pre" | "post", pluginPasses: Array) { - for (let pass of pluginPasses) { - let plugin = pass.plugin; - let fn = plugin[key]; + for (const pass of pluginPasses) { + const plugin = pass.plugin; + const fn = plugin[key]; if (fn) fn.call(pass, this); } } parseInputSourceMap(code: string): string { - let opts = this.opts; + const opts = this.opts; if (opts.inputSourceMap !== false) { - let inputMap = convertSourceMap.fromSource(code); + const inputMap = convertSourceMap.fromSource(code); if (inputMap) { opts.inputSourceMap = inputMap.toObject(); code = convertSourceMap.removeComments(code); @@ -561,7 +561,7 @@ export default class File extends Store { } parseShebang() { - let shebangMatch = shebangRegex.exec(this.code); + const shebangMatch = shebangRegex.exec(this.code); if (shebangMatch) { this.shebang = shebangMatch[0]; this.code = this.code.replace(shebangRegex, ""); @@ -569,7 +569,7 @@ export default class File extends Store { } makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult { - let result = { + const result = { metadata: null, options: this.opts, ignored: !!ignored, @@ -594,10 +594,10 @@ export default class File extends Store { } generate(): BabelFileResult { - let opts = this.opts; - let ast = this.ast; + const opts = this.opts; + const ast = this.ast; - let result: BabelFileResult = { ast }; + const result: BabelFileResult = { ast }; if (!opts.code) return this.makeResult(result); let gen = generate; @@ -605,8 +605,8 @@ export default class File extends Store { gen = opts.generatorOpts.generator; if (typeof gen === "string") { - let dirname = path.dirname(this.opts.filename) || process.cwd(); - let generator = resolve(gen, dirname); + const dirname = path.dirname(this.opts.filename) || process.cwd(); + const generator = resolve(gen, dirname); if (generator) { gen = require(generator).print; } else { @@ -617,7 +617,7 @@ export default class File extends Store { this.log.debug("Generation start"); - let _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts, this.code); + const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts, this.code); result.code = _result.code; result.map = _result.map; diff --git a/packages/babel-core/src/transformation/file/logger.js b/packages/babel-core/src/transformation/file/logger.js index 3573c968e4f9..31bf92ac62ad 100644 --- a/packages/babel-core/src/transformation/file/logger.js +++ b/packages/babel-core/src/transformation/file/logger.js @@ -1,10 +1,10 @@ import type File from "./index"; import buildDebug from "debug/node"; -let verboseDebug = buildDebug("babel:verbose"); -let generalDebug = buildDebug("babel"); +const verboseDebug = buildDebug("babel:verbose"); +const generalDebug = buildDebug("babel"); -let seenDeprecatedMessages = []; +const seenDeprecatedMessages = []; export default class Logger { constructor(file: File, filename: string) { diff --git a/packages/babel-core/src/transformation/file/metadata.js b/packages/babel-core/src/transformation/file/metadata.js index 0183006ffbfb..83b3580819d7 100644 --- a/packages/babel-core/src/transformation/file/metadata.js +++ b/packages/babel-core/src/transformation/file/metadata.js @@ -1,28 +1,28 @@ import * as t from "babel-types"; -export let ModuleDeclaration = { +export const ModuleDeclaration = { enter(path, file) { - let { node } = path; + const { node } = path; if (node.source) { node.source.value = file.resolveModuleSource(node.source.value); } } }; -export let ImportDeclaration = { +export const ImportDeclaration = { exit(path, file) { - let { node } = path; + const { node } = path; - let specifiers = []; - let imported = []; + const specifiers = []; + const imported = []; file.metadata.modules.imports.push({ source: node.source.value, imported, specifiers }); - for (let specifier of (path.get("specifiers"): Array)) { - let local = specifier.node.local.name; + for (const specifier of (path.get("specifiers"): Array)) { + const local = specifier.node.local.name; if (specifier.isImportDefaultSpecifier()) { imported.push("default"); @@ -34,7 +34,7 @@ export let ImportDeclaration = { } if (specifier.isImportSpecifier()) { - let importedName = specifier.node.imported.name; + const importedName = specifier.node.imported.name; imported.push(importedName); specifiers.push({ kind: "named", @@ -55,18 +55,18 @@ export let ImportDeclaration = { }; export function ExportDeclaration(path, file) { - let { node } = path; + const { node } = path; - let source = node.source ? node.source.value : null; - let exports = file.metadata.modules.exports; + const source = node.source ? node.source.value : null; + const exports = file.metadata.modules.exports; // export function foo() {} // export let foo = "bar"; - let declar = path.get("declaration"); + const declar = path.get("declaration"); if (declar.isStatement()) { - let bindings = declar.getBindingIdentifiers(); + const bindings = declar.getBindingIdentifiers(); - for (let name in bindings) { + for (const name in bindings) { exports.exported.push(name); exports.specifiers.push({ kind: "local", @@ -77,8 +77,8 @@ export function ExportDeclaration(path, file) { } if (path.isExportNamedDeclaration() && node.specifiers) { - for (let specifier of (node.specifiers: Array)) { - let exported = specifier.exported.name; + for (const specifier of (node.specifiers: Array)) { + const exported = specifier.exported.name; exports.exported.push(exported); // export foo from "bar"; @@ -100,7 +100,7 @@ export function ExportDeclaration(path, file) { }); } - let local = specifier.local; + const local = specifier.local; if (!local) continue; // export { foo } from "bar"; diff --git a/packages/babel-core/src/transformation/file/options/build-config-chain.js b/packages/babel-core/src/transformation/file/options/build-config-chain.js index 02ce7376413a..f546f45b326a 100644 --- a/packages/babel-core/src/transformation/file/options/build-config-chain.js +++ b/packages/babel-core/src/transformation/file/options/build-config-chain.js @@ -6,15 +6,15 @@ import isAbsolute from "path-is-absolute"; import path from "path"; import fs from "fs"; -let existsCache = {}; -let jsonCache = {}; +const existsCache = {}; +const jsonCache = {}; const BABELIGNORE_FILENAME = ".babelignore"; const BABELRC_FILENAME = ".babelrc"; const PACKAGE_FILENAME = "package.json"; function exists(filename) { - let cached = existsCache[filename]; + const cached = existsCache[filename]; if (cached == null) { return existsCache[filename] = fs.existsSync(filename); } else { @@ -23,8 +23,8 @@ function exists(filename) { } export default function buildConfigChain(opts: Object = {}, log?: Logger) { - let filename = opts.filename; - let builder = new ConfigChainBuilder(log); + const filename = opts.filename; + const builder = new ConfigChainBuilder(log); // resolve all .babelrc files if (opts.babelrc !== false) { @@ -59,20 +59,20 @@ class ConfigChainBuilder { while (loc !== (loc = path.dirname(loc))) { if (!foundConfig) { - let configLoc = path.join(loc, BABELRC_FILENAME); + const configLoc = path.join(loc, BABELRC_FILENAME); if (exists(configLoc)) { this.addConfig(configLoc); foundConfig = true; } - let pkgLoc = path.join(loc, PACKAGE_FILENAME); + const pkgLoc = path.join(loc, PACKAGE_FILENAME); if (!foundConfig && exists(pkgLoc)) { foundConfig = this.addConfig(pkgLoc, "babel", JSON); } } if (!foundIgnore) { - let ignoreLoc = path.join(loc, BABELIGNORE_FILENAME); + const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME); if (exists(ignoreLoc)) { this.addIgnoreConfig(ignoreLoc); foundIgnore = true; @@ -84,7 +84,7 @@ class ConfigChainBuilder { } addIgnoreConfig(loc) { - let file = fs.readFileSync(loc, "utf8"); + const file = fs.readFileSync(loc, "utf8"); let lines = file.split("\n"); lines = lines @@ -107,7 +107,7 @@ class ConfigChainBuilder { this.resolvedConfigs.push(loc); - let content = fs.readFileSync(loc, "utf8"); + const content = fs.readFileSync(loc, "utf8"); let options; try { @@ -144,7 +144,7 @@ class ConfigChainBuilder { // add extends clause if (options.extends) { - let extendsLoc = resolve(options.extends, dirname); + const extendsLoc = resolve(options.extends, dirname); if (extendsLoc) { this.addConfig(extendsLoc); } else { @@ -162,7 +162,7 @@ class ConfigChainBuilder { // env let envOpts; - let envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; + const envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; if (options.env) { envOpts = options.env[envKey]; delete options.env; diff --git a/packages/babel-core/src/transformation/file/options/index.js b/packages/babel-core/src/transformation/file/options/index.js index 69792cc65eac..c5f8a73c5175 100644 --- a/packages/babel-core/src/transformation/file/options/index.js +++ b/packages/babel-core/src/transformation/file/options/index.js @@ -4,7 +4,7 @@ import config from "./config"; export { config }; export function normaliseOptions(options: Object = {}): Object { - for (let key in options) { + for (const key in options) { let val = options[key]; if (val == null) continue; @@ -12,7 +12,7 @@ export function normaliseOptions(options: Object = {}): Object { if (opt && opt.alias) opt = config[opt.alias]; if (!opt) continue; - let parser = parsers[opt.type]; + const parser = parsers[opt.type]; if (parser) val = parser(val); options[key] = val; diff --git a/packages/babel-core/src/transformation/file/options/option-manager.js b/packages/babel-core/src/transformation/file/options/option-manager.js index ed0eab6a4884..c4736355a6a0 100644 --- a/packages/babel-core/src/transformation/file/options/option-manager.js +++ b/packages/babel-core/src/transformation/file/options/option-manager.js @@ -53,7 +53,7 @@ export default class OptionManager { }>; static memoisePluginContainer(fn, loc, i, alias) { - for (let cache of (OptionManager.memoisedPlugins: Array)) { + for (const cache of (OptionManager.memoisedPlugins: Array)) { if (cache.container === fn) return cache.plugin; } @@ -66,7 +66,7 @@ export default class OptionManager { } if (typeof obj === "object") { - let plugin = new Plugin(obj, alias); + const plugin = new Plugin(obj, alias); OptionManager.memoisedPlugins.push({ container: fn, plugin: plugin @@ -78,10 +78,10 @@ export default class OptionManager { } static createBareOptions() { - let opts = {}; + const opts = {}; - for (let key in config) { - let opt = config[key]; + for (const key in config) { + const opt = config[key]; opts[key] = clone(opt.default); } @@ -120,11 +120,11 @@ export default class OptionManager { plugin = val; } - let alias = typeof plugin === "string" ? plugin : `${loc}$${i}`; + const alias = typeof plugin === "string" ? plugin : `${loc}$${i}`; // allow plugins to be specified as strings if (typeof plugin === "string") { - let pluginLoc = resolvePlugin(plugin, dirname); + const pluginLoc = resolvePlugin(plugin, dirname); if (pluginLoc) { plugin = require(pluginLoc); } else { @@ -164,7 +164,7 @@ export default class OptionManager { } // - let opts = cloneDeepWith(rawOpts, (val) => { + const opts = cloneDeepWith(rawOpts, (val) => { if (val instanceof Plugin) { return val; } @@ -174,16 +174,16 @@ export default class OptionManager { dirname = dirname || process.cwd(); loc = loc || alias; - for (let key in opts) { - let option = config[key]; + for (const key in opts) { + const option = config[key]; // check for an unknown option if (!option && this.log) { if (removed[key]) { this.log.error(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`, ReferenceError); } else { - let unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`; - let presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; + const unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`; + const presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; this.log.error(`${unknownOptErr}\n\n${presetConfigErr}`, ReferenceError); } @@ -316,11 +316,11 @@ export default class OptionManager { } normaliseOptions() { - let opts = this.options; + const opts = this.options; - for (let key in config) { - let option = config[key]; - let val = opts[key]; + for (const key in config) { + const option = config[key]; + const val = opts[key]; // optional if (!val && option.optional) continue; @@ -335,7 +335,7 @@ export default class OptionManager { } init(opts: Object = {}): Object { - for (let config of buildConfigChain(opts, this.log)) { + for (const config of buildConfigChain(opts, this.log)) { this.mergeOptions(config); } diff --git a/packages/babel-core/src/transformation/file/options/parsers.js b/packages/babel-core/src/transformation/file/options/parsers.js index fa8dbae260c9..2dcf5b7a71ac 100644 --- a/packages/babel-core/src/transformation/file/options/parsers.js +++ b/packages/babel-core/src/transformation/file/options/parsers.js @@ -1,7 +1,7 @@ import slash from "slash"; import * as util from "../../../util"; -export let filename = slash; +export const filename = slash; export function boolean(val: any): boolean { return !!val; diff --git a/packages/babel-core/src/transformation/internal-plugins/block-hoist.js b/packages/babel-core/src/transformation/internal-plugins/block-hoist.js index de8bedf5bbfc..d546b9abd5bd 100644 --- a/packages/babel-core/src/transformation/internal-plugins/block-hoist.js +++ b/packages/babel-core/src/transformation/internal-plugins/block-hoist.js @@ -20,7 +20,7 @@ export default new Plugin({ exit({ node }) { let hasChange = false; for (let i = 0; i < node.body.length; i++) { - let bodyNode = node.body[i]; + const bodyNode = node.body[i]; if (bodyNode && bodyNode._blockHoist != null) { hasChange = true; break; diff --git a/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js b/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js index 572b9bb37967..6b5995fc27d2 100644 --- a/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js +++ b/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js @@ -41,10 +41,10 @@ function shouldShadow(path, shadowPath) { function remap(path, key) { // ensure that we're shadowed - let shadowPath = path.inShadow(key); + const shadowPath = path.inShadow(key); if (!shouldShadow(path, shadowPath)) return; - let shadowFunction = path.node._shadowedFunctionLiteral; + const shadowFunction = path.node._shadowedFunctionLiteral; let currentFunction; let passedShadowFunction = false; @@ -91,15 +91,15 @@ function remap(path, key) { // binding since arrow function syntax already does that. if (!passedShadowFunction) return; - let cached = fnPath.getData(key); + const cached = fnPath.getData(key); if (cached) return path.replaceWith(cached); - let id = path.scope.generateUidIdentifier(key); + const id = path.scope.generateUidIdentifier(key); fnPath.setData(key, id); - let classPath = fnPath.findParent((p) => p.isClass()); - let hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); + const classPath = fnPath.findParent((p) => p.isClass()); + const hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); if (key === "this" && fnPath.isMethod({kind: "constructor"}) && hasSuperClass) { fnPath.scope.push({ id }); diff --git a/packages/babel-core/src/transformation/pipeline.js b/packages/babel-core/src/transformation/pipeline.js index 12b1edbba3e5..15b3f0cffddd 100644 --- a/packages/babel-core/src/transformation/pipeline.js +++ b/packages/babel-core/src/transformation/pipeline.js @@ -11,7 +11,7 @@ export default class Pipeline { } pretransform(code: string, opts?: Object): BabelFileResult { - let file = new File(opts, this); + const file = new File(opts, this); return file.wrap(code, function () { file.addCode(code); file.parseCode(code); @@ -20,7 +20,7 @@ export default class Pipeline { } transform(code: string, opts?: Object): BabelFileResult { - let file = new File(opts, this); + const file = new File(opts, this); return file.wrap(code, function () { file.addCode(code); file.parseCode(code); @@ -40,7 +40,7 @@ export default class Pipeline { transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult { ast = normalizeAst(ast); - let file = new File(opts, this); + const file = new File(opts, this); return file.wrap(code, function () { file.addCode(code); file.addAst(ast); diff --git a/packages/babel-core/src/transformation/plugin.js b/packages/babel-core/src/transformation/plugin.js index afca4c882bf9..f3461ae9bf0d 100644 --- a/packages/babel-core/src/transformation/plugin.js +++ b/packages/babel-core/src/transformation/plugin.js @@ -31,7 +31,7 @@ export default class Plugin extends Store { visitor: Object; take(key) { - let val = this.raw[key]; + const val = this.raw[key]; delete this.raw[key]; return val; } @@ -40,13 +40,13 @@ export default class Plugin extends Store { if (!target[key]) return this[key]; if (!this[key]) return target[key]; - let fns: Array = [target[key], this[key]]; + const fns: Array = [target[key], this[key]]; return function (...args) { let val; - for (let fn of fns) { + for (const fn of fns) { if (fn) { - let ret = fn.apply(this, args); + const ret = fn.apply(this, args); if (ret != null) val = ret; } } @@ -77,13 +77,13 @@ export default class Plugin extends Store { this.maybeInherit(loc); - for (let key in this.raw) { + for (const key in this.raw) { throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); } } normaliseVisitor(visitor: Object): Object { - for (let key of GLOBAL_VISITOR_PROPS) { + for (const key of GLOBAL_VISITOR_PROPS) { if (visitor[key]) { throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes."); } diff --git a/packages/babel-core/src/util.js b/packages/babel-core/src/util.js index 4da7503e8cbf..97726e264016 100644 --- a/packages/babel-core/src/util.js +++ b/packages/babel-core/src/util.js @@ -15,8 +15,8 @@ export { inherits, inspect } from "util"; */ export function canCompile(filename: string, altExts?: Array): boolean { - let exts = altExts || canCompile.EXTENSIONS; - let ext = path.extname(filename); + const exts = altExts || canCompile.EXTENSIONS; + const ext = path.extname(filename); return includes(exts, ext); } @@ -63,7 +63,7 @@ export function regexify(val: any): RegExp { if (startsWith(val, "./") || startsWith(val, "*/")) val = val.slice(2); if (startsWith(val, "**/")) val = val.slice(3); - let regex = minimatch.makeRe(val, { nocase: true }); + const regex = minimatch.makeRe(val, { nocase: true }); return new RegExp(regex.source.slice(1, -1), "i"); } @@ -119,12 +119,12 @@ export function shouldIgnore( filename = filename.replace(/\\/g, "/"); if (only) { - for (let pattern of only) { + for (const pattern of only) { if (_shouldIgnore(pattern, filename)) return false; } return true; } else if (ignore.length) { - for (let pattern of ignore) { + for (const pattern of ignore) { if (_shouldIgnore(pattern, filename)) return true; } } diff --git a/packages/babel-core/test/api.js b/packages/babel-core/test/api.js index 0b997fb4a025..70823258e5cf 100644 --- a/packages/babel-core/test/api.js +++ b/packages/babel-core/test/api.js @@ -1,9 +1,9 @@ -let babel = require("../lib/api/node"); -let buildExternalHelpers = require("../lib/tools/build-external-helpers"); -let sourceMap = require("source-map"); -let assert = require("assert"); -let Plugin = require("../lib/transformation/plugin"); -let generator = require("babel-generator").default; +const babel = require("../lib/api/node"); +const buildExternalHelpers = require("../lib/tools/build-external-helpers"); +const sourceMap = require("source-map"); +const assert = require("assert"); +const Plugin = require("../lib/transformation/plugin"); +const generator = require("babel-generator").default; function assertIgnored(result) { assert.ok(result.ignored); @@ -23,7 +23,7 @@ function transformAsync(code, opts) { } describe("parser and generator options", function() { - let recast = { + const recast = { parse: function(code, opts) { return opts.parser.parse(code); }, @@ -46,13 +46,13 @@ describe("parser and generator options", function() { } it("options", function() { - let string = "original;"; + const string = "original;"; assert.deepEqual(newTransform(string).ast, babel.transform(string).ast); assert.equal(newTransform(string).code, string); }); it("experimental syntax", function() { - let experimental = "var a: number = 1;"; + const experimental = "var a: number = 1;"; assert.deepEqual(newTransform(experimental).ast, babel.transform(experimental, { parserOpts: { @@ -82,7 +82,7 @@ describe("parser and generator options", function() { }); it("other options", function() { - let experimental = "if (true) {\n import a from 'a';\n}"; + const experimental = "if (true) {\n import a from 'a';\n}"; assert.notEqual(newTransform(experimental).ast, babel.transform(experimental, { parserOpts: { @@ -199,7 +199,7 @@ describe("api", function () { new Plugin({ visitor: { Function: function(path) { - let alias = path.scope.getProgramParent().path.get("body")[0].node; + const alias = path.scope.getProgramParent().path.get("body")[0].node; if (!babel.types.isTypeAlias(alias)) return; // In case of `passPerPreset` being `false`, the @@ -264,7 +264,7 @@ describe("api", function () { }); it("source map merging", function () { - let result = babel.transform([ + const result = babel.transform([ "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }", "", "let Foo = function Foo() {", @@ -288,7 +288,7 @@ describe("api", function () { "};" ].join("\n"), result.code); - let consumer = new sourceMap.SourceMapConsumer(result.map); + const consumer = new sourceMap.SourceMapConsumer(result.map); assert.deepEqual(consumer.originalPositionFor({ line: 7, @@ -318,7 +318,7 @@ describe("api", function () { auxiliaryCommentBefore: "before", auxiliaryCommentAfter: "after", plugins: [function (babel) { - let t = babel.types; + const t = babel.types; return { visitor: { Program: function (path) { @@ -539,8 +539,8 @@ describe("api", function () { }); describe("env option", function () { - let oldBabelEnv = process.env.BABEL_ENV; - let oldNodeEnv = process.env.NODE_ENV; + const oldBabelEnv = process.env.BABEL_ENV; + const oldNodeEnv = process.env.NODE_ENV; setup(function () { // Tests need to run with the default and specific values for these. They @@ -555,7 +555,7 @@ describe("api", function () { }); it("default", function () { - let result = babel.transform("foo;", { + const result = babel.transform("foo;", { env: { development: { code: false } } @@ -566,7 +566,7 @@ describe("api", function () { it("BABEL_ENV", function () { process.env.BABEL_ENV = "foo"; - let result = babel.transform("foo;", { + const result = babel.transform("foo;", { env: { foo: { code: false } } @@ -576,7 +576,7 @@ describe("api", function () { it("NODE_ENV", function () { process.env.NODE_ENV = "foo"; - let result = babel.transform("foo;", { + const result = babel.transform("foo;", { env: { foo: { code: false } } @@ -586,8 +586,8 @@ describe("api", function () { }); it("resolveModuleSource option", function () { - let actual = "import foo from \"foo-import-default\";\nimport \"foo-import-bare\";\nexport { foo } from \"foo-export-named\";"; - let expected = "import foo from \"resolved/foo-import-default\";\nimport \"resolved/foo-import-bare\";\nexport { foo } from \"resolved/foo-export-named\";"; + const actual = "import foo from \"foo-import-default\";\nimport \"foo-import-bare\";\nexport { foo } from \"foo-export-named\";"; + const expected = "import foo from \"resolved/foo-import-default\";\nimport \"resolved/foo-import-bare\";\nexport { foo } from \"resolved/foo-export-named\";"; return transformAsync(actual, { resolveModuleSource: function (originalSource) { @@ -600,25 +600,25 @@ describe("api", function () { describe("buildExternalHelpers", function () { it("all", function () { - let script = buildExternalHelpers(); + const script = buildExternalHelpers(); assert.ok(script.indexOf("classCallCheck") >= -1); assert.ok(script.indexOf("inherits") >= 0); }); it("whitelist", function () { - let script = buildExternalHelpers(["inherits"]); + const script = buildExternalHelpers(["inherits"]); assert.ok(script.indexOf("classCallCheck") === -1); assert.ok(script.indexOf("inherits") >= 0); }); it("empty whitelist", function () { - let script = buildExternalHelpers([]); + const script = buildExternalHelpers([]); assert.ok(script.indexOf("classCallCheck") === -1); assert.ok(script.indexOf("inherits") === -1); }); it("underscored", function () { - let script = buildExternalHelpers(["typeof"]); + const script = buildExternalHelpers(["typeof"]); assert.ok(script.indexOf("typeof") >= 0); }); }); diff --git a/packages/babel-core/test/browserify.js b/packages/babel-core/test/browserify.js index 9923f6c52ea8..730ace945ab7 100644 --- a/packages/babel-core/test/browserify.js +++ b/packages/babel-core/test/browserify.js @@ -1,11 +1,11 @@ -let browserify = require("browserify"); -let assert = require("assert"); -let path = require("path"); -let vm = require("vm"); +const browserify = require("browserify"); +const assert = require("assert"); +const path = require("path"); +const vm = require("vm"); describe("browserify", function() { it("babel/register may be used without breaking browserify", function(done) { - let bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js")); + const bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js")); bundler.bundle(function(err, bundle) { if (err) return done(err); diff --git a/packages/babel-core/test/config-chain.js b/packages/babel-core/test/config-chain.js index 0a0b952d5123..95d17eeb15dc 100644 --- a/packages/babel-core/test/config-chain.js +++ b/packages/babel-core/test/config-chain.js @@ -1,9 +1,9 @@ -let assert = require("assert"); -let path = require("path"); -let buildConfigChain = require("../lib/transformation/file/options/build-config-chain"); +const assert = require("assert"); +const path = require("path"); +const buildConfigChain = require("../lib/transformation/file/options/build-config-chain"); function fixture() { - let args = [__dirname, "fixtures", "config"]; + const args = [__dirname, "fixtures", "config"]; for (let i = 0; i < arguments.length; i ++) { args.push(arguments[i]); } @@ -28,11 +28,11 @@ describe("buildConfigChain", function () { }); it("dir1", function () { - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("dir1", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: [ @@ -77,11 +77,11 @@ describe("buildConfigChain", function () { }); it("dir2", function () { - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("dir2", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: [ @@ -116,11 +116,11 @@ describe("buildConfigChain", function () { }); it("env - base", function () { - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("env", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: [ @@ -157,11 +157,11 @@ describe("buildConfigChain", function () { it("env - foo", function () { process.env.NODE_ENV = "foo"; - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("env", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: [ @@ -209,11 +209,11 @@ describe("buildConfigChain", function () { process.env.NODE_ENV = "foo"; // overridden process.env.NODE_ENV = "bar"; - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("env", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: [ @@ -261,11 +261,11 @@ describe("buildConfigChain", function () { it("env - foo", function () { process.env.NODE_ENV = "foo"; - let chain = buildConfigChain({ + const chain = buildConfigChain({ filename: fixture("pkg", "src.js") }); - let expected = [ + const expected = [ { options: { plugins: ["pkg-plugin"] diff --git a/packages/babel-core/test/evaluation.js b/packages/babel-core/test/evaluation.js index 1af3bc739933..4378bb417649 100644 --- a/packages/babel-core/test/evaluation.js +++ b/packages/babel-core/test/evaluation.js @@ -1,14 +1,14 @@ -let traverse = require("babel-traverse").default; -let assert = require("assert"); -let parse = require("babylon").parse; +const traverse = require("babel-traverse").default; +const assert = require("assert"); +const parse = require("babylon").parse; describe("evaluation", function () { function addTest(code, type, value, notConfident) { it(type + ": " + code, function () { - let visitor = {}; + const visitor = {}; visitor[type] = function (path) { - let evaluate = path.evaluate(); + const evaluate = path.evaluate(); assert.equal(evaluate.confident, !notConfident); assert.deepEqual(evaluate.value, value); }; diff --git a/packages/babel-core/test/get-possible-plugin-names.js b/packages/babel-core/test/get-possible-plugin-names.js index 4a9ec2d08030..d9d730bd6cda 100644 --- a/packages/babel-core/test/get-possible-plugin-names.js +++ b/packages/babel-core/test/get-possible-plugin-names.js @@ -1,5 +1,5 @@ -let assert = require("assert"); -let getPossiblePluginNames = require("../lib/helpers/get-possible-plugin-names"); +const assert = require("assert"); +const getPossiblePluginNames = require("../lib/helpers/get-possible-plugin-names"); describe("getPossiblePluginNames", function () { it("adds the babel-plugin prefix", function() { diff --git a/packages/babel-core/test/get-possible-preset-names.js b/packages/babel-core/test/get-possible-preset-names.js index 88f9166c8388..64de8897b884 100644 --- a/packages/babel-core/test/get-possible-preset-names.js +++ b/packages/babel-core/test/get-possible-preset-names.js @@ -1,5 +1,5 @@ -let assert = require("assert"); -let getPossiblePresetNames = require("../lib/helpers/get-possible-preset-names"); +const assert = require("assert"); +const getPossiblePresetNames = require("../lib/helpers/get-possible-preset-names"); describe("getPossiblePresetNames", function () { it("adds the babel-preset prefix", function() { diff --git a/packages/babel-core/test/option-manager.js b/packages/babel-core/test/option-manager.js index 592c431d5481..2606a4bca0d6 100644 --- a/packages/babel-core/test/option-manager.js +++ b/packages/babel-core/test/option-manager.js @@ -17,7 +17,7 @@ describe("option-manager", () => { it("throws for removed babel 5 options", () => { return assert.throws( () => { - let opt = new OptionManager(new Logger(null, "unknown")); + const opt = new OptionManager(new Logger(null, "unknown")); opt.init({ "randomOption": true }); @@ -29,7 +29,7 @@ describe("option-manager", () => { it("throws for removed babel 5 options", () => { return assert.throws( () => { - let opt = new OptionManager(new Logger(null, "unknown")); + const opt = new OptionManager(new Logger(null, "unknown")); opt.init({ "auxiliaryComment": true, "blacklist": true @@ -42,7 +42,7 @@ describe("option-manager", () => { it("throws for resolved but erroring preset", () => { return assert.throws( () => { - let opt = new OptionManager(new Logger(null, "unknown")); + const opt = new OptionManager(new Logger(null, "unknown")); opt.init({ "presets": [path.join(__dirname, "fixtures/option-manager/not-a-preset")] }); @@ -54,7 +54,7 @@ describe("option-manager", () => { it("throws for invalid preset configuration", function() { return assert.throws( function () { - let opt = new OptionManager(new Logger(null, "unknown")); + const opt = new OptionManager(new Logger(null, "unknown")); opt.init({ "presets": [{ option: "value" }] }); @@ -67,8 +67,8 @@ describe("option-manager", () => { describe("presets", function () { function presetTest(name) { it(name, function () { - let opt = new OptionManager(new Logger(null, "unknown")); - let options = opt.init({ + const opt = new OptionManager(new Logger(null, "unknown")); + const options = opt.init({ "presets": [path.join(__dirname, "fixtures/option-manager/presets", name)] }); diff --git a/packages/babel-core/test/path.js b/packages/babel-core/test/path.js index c76fc31e59bd..e60c68c9f8b6 100644 --- a/packages/babel-core/test/path.js +++ b/packages/babel-core/test/path.js @@ -1,12 +1,12 @@ -let transform = require("../lib/api/node").transform; -let Plugin = require("../lib/transformation/plugin"); -let chai = require("chai"); +const transform = require("../lib/api/node").transform; +const Plugin = require("../lib/transformation/plugin"); +const chai = require("chai"); describe("traversal path", function () { it("replaceWithSourceString", function () { - let expectCode = "function foo() {}"; + const expectCode = "function foo() {}"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { FunctionDeclaration: function (path) { @@ -20,9 +20,9 @@ describe("traversal path", function () { }); it("replaceWith (arrow expression body to block statement body)", function () { - let expectCode = "var fn = () => true;"; + const expectCode = "var fn = () => true;"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ArrowFunctionExpression: function (path) { @@ -45,9 +45,9 @@ describe("traversal path", function () { }); it("replaceWith (arrow block statement body to expression body)", function () { - let expectCode = "var fn = () => { return true; }"; + const expectCode = "var fn = () => { return true; }"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ArrowFunctionExpression: function (path) { @@ -64,9 +64,9 @@ describe("traversal path", function () { }); it("replaceWith (for-in left expression to variable declaration)", function () { - let expectCode = "for (KEY in right);"; + const expectCode = "for (KEY in right);"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForInStatement: function (path) { @@ -90,9 +90,9 @@ describe("traversal path", function () { }); it("replaceWith (for-in left variable declaration to expression)", function () { - let expectCode = "for (var KEY in right);"; + const expectCode = "for (var KEY in right);"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForInStatement: function (path) { @@ -109,9 +109,9 @@ describe("traversal path", function () { }); it("replaceWith (for-loop left expression to variable declaration)", function () { - let expectCode = "for (KEY;;);"; + const expectCode = "for (KEY;;);"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForStatement: function (path) { @@ -135,9 +135,9 @@ describe("traversal path", function () { }); it("replaceWith (for-loop left variable declaration to expression)", function () { - let expectCode = "for (var KEY;;);"; + const expectCode = "for (var KEY;;);"; - let actualCode = transform(expectCode, { + const actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForStatement: function (path) { diff --git a/packages/babel-core/test/resolution.js b/packages/babel-core/test/resolution.js index bdffce466d98..622ddac038c8 100644 --- a/packages/babel-core/test/resolution.js +++ b/packages/babel-core/test/resolution.js @@ -1,14 +1,14 @@ -let assert = require("assert"); -let async = require("async"); -let babel = require("../lib/api/node"); -let fs = require("fs"); -let path = require("path"); +const assert = require("assert"); +const async = require("async"); +const babel = require("../lib/api/node"); +const fs = require("fs"); +const path = require("path"); // Test that plugins & presets are resolved relative to `filename`. describe("addon resolution", function () { it("addon resolution", function (done) { - let fixtures = {}; - let paths = {}; + const fixtures = {}; + const paths = {}; paths.fixtures = path.join( __dirname, @@ -33,7 +33,7 @@ describe("addon resolution", function () { function fixturesReady (err) { if (err) return done(err); - let actual = babel.transform(fixtures.actual, { + const actual = babel.transform(fixtures.actual, { filename: paths.actual, plugins: ["addons/plugin"], presets: ["addons/preset"], diff --git a/packages/babel-core/test/util.js b/packages/babel-core/test/util.js index ae1e83e91399..1e879f41a585 100644 --- a/packages/babel-core/test/util.js +++ b/packages/babel-core/test/util.js @@ -1,6 +1,6 @@ -let assert = require("assert"); -let util = require("../lib/util"); -let t = require("babel-types"); +const assert = require("assert"); +const util = require("../lib/util"); +const t = require("babel-types"); describe("util", function () { it("canCompile", function () { @@ -36,7 +36,7 @@ describe("util", function () { assert.deepEqual(util.list(["foo", "bar"]), ["foo", "bar"]); assert.deepEqual(util.list(/foo/), [/foo/]); - let date = new Date; + const date = new Date; assert.deepEqual(util.list(date), [date]); }); @@ -84,8 +84,8 @@ describe("util", function () { }); it("shouldIgnore", function () { - let reIgnore = /\-reIgnore\.js/; - let fnIgnore = function (src) { + const reIgnore = /\-reIgnore\.js/; + const fnIgnore = function (src) { if (src.indexOf("fnIgnore") > 0) { return true; } diff --git a/packages/babel-generator/src/buffer.js b/packages/babel-generator/src/buffer.js index 69c61db86470..72894c440a25 100644 --- a/packages/babel-generator/src/buffer.js +++ b/packages/babel-generator/src/buffer.js @@ -153,7 +153,7 @@ export default class Buffer { source(prop: string, loc: Location): void { if (prop && !loc) return; - let pos = loc ? loc[prop] : null; + const pos = loc ? loc[prop] : null; this._sourcePosition.identifierName = loc && loc.identifierName || null; this._sourcePosition.line = pos ? pos.line : null; @@ -169,10 +169,10 @@ export default class Buffer { if (!this._map) return cb(); // Use the call stack to manage a stack of "source location" data. - let originalLine = this._sourcePosition.line; - let originalColumn = this._sourcePosition.column; - let originalFilename = this._sourcePosition.filename; - let originalIdentifierName = this._sourcePosition.identifierName; + const originalLine = this._sourcePosition.line; + const originalColumn = this._sourcePosition.column; + const originalFilename = this._sourcePosition.filename; + const originalIdentifierName = this._sourcePosition.identifierName; this.source(prop, loc); diff --git a/packages/babel-generator/src/generators/base.js b/packages/babel-generator/src/generators/base.js index dec9fe11bf3e..ec2dd763641c 100644 --- a/packages/babel-generator/src/generators/base.js +++ b/packages/babel-generator/src/generators/base.js @@ -15,7 +15,7 @@ export function BlockStatement(node: Object) { this.token("{"); this.printInnerComments(node); - let hasDirectives = node.directives && node.directives.length; + const hasDirectives = node.directives && node.directives.length; if (node.body.length || hasDirectives) { this.newline(); diff --git a/packages/babel-generator/src/generators/expressions.js b/packages/babel-generator/src/generators/expressions.js index b38cebed54a6..c4c581eddf16 100644 --- a/packages/babel-generator/src/generators/expressions.js +++ b/packages/babel-generator/src/generators/expressions.js @@ -94,7 +94,7 @@ export function CallExpression(node: Object) { this.token("("); - let isPrettyCall = node._prettyCall; + const isPrettyCall = node._prettyCall; let separator; if (isPrettyCall) { @@ -127,15 +127,15 @@ function buildYieldAwait(keyword: string) { if (node.argument) { this.space(); - let terminatorState = this.startTerminatorless(); + const terminatorState = this.startTerminatorless(); this.print(node.argument, node); this.endTerminatorless(terminatorState); } }; } -export let YieldExpression = buildYieldAwait("yield"); -export let AwaitExpression = buildYieldAwait("await"); +export const YieldExpression = buildYieldAwait("yield"); +export const AwaitExpression = buildYieldAwait("await"); export function EmptyStatement() { this.semicolon(true /* force */); @@ -159,7 +159,7 @@ export function AssignmentPattern(node: Object) { export function AssignmentExpression(node: Object, parent: Object) { // Somewhere inside a for statement `init` node but doesn't usually // needs a paren except for `in` expressions: `for (a in b ? a : b;;)` - let parens = this.inForStatementInitCounter && node.operator === "in" && + const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); if (parens) { diff --git a/packages/babel-generator/src/generators/flow.js b/packages/babel-generator/src/generators/flow.js index 9ef56bdde494..668ba0e2b3c1 100644 --- a/packages/babel-generator/src/generators/flow.js +++ b/packages/babel-generator/src/generators/flow.js @@ -264,7 +264,7 @@ export function ObjectTypeAnnotation(node: Object) { this.token("{"); } - let props = node.properties.concat(node.callProperties, node.indexers); + const props = node.properties.concat(node.callProperties, node.indexers); if (props.length) { this.space(); diff --git a/packages/babel-generator/src/generators/jsx.js b/packages/babel-generator/src/generators/jsx.js index 7da237ff6a90..521b479ae086 100644 --- a/packages/babel-generator/src/generators/jsx.js +++ b/packages/babel-generator/src/generators/jsx.js @@ -47,12 +47,12 @@ export function JSXText(node: Object) { } export function JSXElement(node: Object) { - let open = node.openingElement; + const open = node.openingElement; this.print(open, node); if (open.selfClosing) return; this.indent(); - for (let child of (node.children: Array)) { + for (const child of (node.children: Array)) { this.print(child, node); } this.dedent(); diff --git a/packages/babel-generator/src/generators/methods.js b/packages/babel-generator/src/generators/methods.js index 720aa0c87bd3..97bbcd312976 100644 --- a/packages/babel-generator/src/generators/methods.js +++ b/packages/babel-generator/src/generators/methods.js @@ -17,8 +17,8 @@ export function _params(node: Object) { } export function _method(node: Object) { - let kind = node.kind; - let key = node.key; + const kind = node.kind; + const key = node.key; if (kind === "method" || kind === "init") { if (node.generator) { diff --git a/packages/babel-generator/src/generators/modules.js b/packages/babel-generator/src/generators/modules.js index 6a87a0251253..59f19aa8dd85 100644 --- a/packages/babel-generator/src/generators/modules.js +++ b/packages/babel-generator/src/generators/modules.js @@ -69,7 +69,7 @@ export function ExportDefaultDeclaration() { function ExportDeclaration(node: Object) { if (node.declaration) { - let declar = node.declaration; + const declar = node.declaration; this.print(declar, node); if (!t.isStatement(declar)) this.semicolon(); } else { @@ -78,12 +78,12 @@ function ExportDeclaration(node: Object) { this.space(); } - let specifiers = node.specifiers.slice(0); + const specifiers = node.specifiers.slice(0); // print "special" specifiers first let hasSpecial = false; while (true) { - let first = specifiers[0]; + const first = specifiers[0]; if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { hasSpecial = true; this.print(specifiers.shift(), node); @@ -126,11 +126,11 @@ export function ImportDeclaration(node: Object) { this.space(); } - let specifiers = node.specifiers.slice(0); + const specifiers = node.specifiers.slice(0); if (specifiers && specifiers.length) { // print "special" specifiers first while (true) { - let first = specifiers[0]; + const first = specifiers[0]; if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { this.print(specifiers.shift(), node); if (specifiers.length) { diff --git a/packages/babel-generator/src/generators/statements.js b/packages/babel-generator/src/generators/statements.js index a5ec4818820f..b9e8e736b344 100644 --- a/packages/babel-generator/src/generators/statements.js +++ b/packages/babel-generator/src/generators/statements.js @@ -17,7 +17,7 @@ export function IfStatement(node: Object) { this.token(")"); this.space(); - let needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); + const needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); if (needsBlock) { this.token("{"); this.newline(); @@ -80,7 +80,7 @@ export function WhileStatement(node: Object) { this.printBlock(node); } -let buildForXStatement = function (op) { +const buildForXStatement = function (op) { return function (node: Object) { this.word("for"); this.space(); @@ -101,9 +101,9 @@ let buildForXStatement = function (op) { }; }; -export let ForInStatement = buildForXStatement("in"); -export let ForOfStatement = buildForXStatement("of"); -export let ForAwaitStatement = buildForXStatement("await"); +export const ForInStatement = buildForXStatement("in"); +export const ForOfStatement = buildForXStatement("of"); +export const ForAwaitStatement = buildForXStatement("await"); export function DoWhileStatement(node: Object) { this.word("do"); @@ -122,11 +122,11 @@ function buildLabelStatement(prefix, key = "label") { return function (node: Object) { this.word(prefix); - let label = node[key]; + const label = node[key]; if (label) { this.space(); - let terminatorState = this.startTerminatorless(); + const terminatorState = this.startTerminatorless(); this.print(label, node); this.endTerminatorless(terminatorState); } @@ -135,10 +135,10 @@ function buildLabelStatement(prefix, key = "label") { }; } -export let ContinueStatement = buildLabelStatement("continue"); -export let ReturnStatement = buildLabelStatement("return", "argument"); -export let BreakStatement = buildLabelStatement("break"); -export let ThrowStatement = buildLabelStatement("throw", "argument"); +export const ContinueStatement = buildLabelStatement("continue"); +export const ReturnStatement = buildLabelStatement("return", "argument"); +export const BreakStatement = buildLabelStatement("break"); +export const ThrowStatement = buildLabelStatement("throw", "argument"); export function LabeledStatement(node: Object) { this.print(node.label, node); @@ -242,7 +242,7 @@ export function VariableDeclaration(node: Object, parent: Object) { let hasInits = false; // don't add whitespace to loop heads if (!t.isFor(parent)) { - for (let declar of (node.declarations: Array)) { + for (const declar of (node.declarations: Array)) { if (declar.init) { // has an init so let's split it up over multiple lines hasInits = true; diff --git a/packages/babel-generator/src/generators/template-literals.js b/packages/babel-generator/src/generators/template-literals.js index 127b64b0cd96..a49b8615edb9 100644 --- a/packages/babel-generator/src/generators/template-literals.js +++ b/packages/babel-generator/src/generators/template-literals.js @@ -7,13 +7,13 @@ export function TemplateElement(node: Object, parent: Object) { const isFirst = parent.quasis[0] === node; const isLast = parent.quasis[parent.quasis.length - 1] === node; - let value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); this.token(value); } export function TemplateLiteral(node: Object) { - let quasis = node.quasis; + const quasis = node.quasis; for (let i = 0; i < quasis.length; i++) { this.print(quasis[i], node); diff --git a/packages/babel-generator/src/generators/types.js b/packages/babel-generator/src/generators/types.js index 3f803c8e11eb..fa8498aff7d1 100644 --- a/packages/babel-generator/src/generators/types.js +++ b/packages/babel-generator/src/generators/types.js @@ -32,7 +32,7 @@ export { }; export function ObjectExpression(node: Object) { - let props = node.properties; + const props = node.properties; this.token("{"); this.printInnerComments(node); @@ -84,14 +84,14 @@ export function ObjectProperty(node: Object) { } export function ArrayExpression(node: Object) { - let elems = node.elements; - let len = elems.length; + const elems = node.elements; + const len = elems.length; this.token("["); this.printInnerComments(node); for (let i = 0; i < elems.length; i++) { - let elem = elems[i]; + const elem = elems[i]; if (elem) { if (i > 0) this.space(); this.print(elem, node); @@ -136,7 +136,7 @@ export function NumericLiteral(node: Object) { } export function StringLiteral(node: Object, parent: Object) { - let raw = this.getPossibleRaw(node); + const raw = this.getPossibleRaw(node); if (!this.format.minified && raw != null) { this.token(raw); return; @@ -150,7 +150,7 @@ export function StringLiteral(node: Object, parent: Object) { if (this.format.jsonCompatibleStrings) { opts.json = true; } - let val = jsesc(node.value, opts); + const val = jsesc(node.value, opts); return this.token(val); } diff --git a/packages/babel-generator/src/index.js b/packages/babel-generator/src/index.js index c212cbdf7c05..a3031f16796e 100644 --- a/packages/babel-generator/src/index.js +++ b/packages/babel-generator/src/index.js @@ -14,8 +14,8 @@ class Generator extends Printer { opts = opts || {}; const tokens = ast.tokens || []; - let format = normalizeOptions(code, opts, tokens); - let map = opts.sourceMaps ? new SourceMap(opts, code) : null; + const format = normalizeOptions(code, opts, tokens); + const map = opts.sourceMaps ? new SourceMap(opts, code) : null; super(format, map, tokens); this.ast = ast; @@ -44,11 +44,11 @@ class Generator extends Printer { function normalizeOptions(code, opts, tokens): Format { let style = " "; if (code && typeof code === "string") { - let indent = detectIndent(code).indent; + const indent = detectIndent(code).indent; if (indent && indent !== " ") style = indent; } - let format = { + const format = { auxiliaryCommentBefore: opts.auxiliaryCommentBefore, auxiliaryCommentAfter: opts.auxiliaryCommentAfter, shouldPrintComment: opts.shouldPrintComment, @@ -101,7 +101,7 @@ function findCommonStringDelimiter(code, tokens) { return DEFAULT_STRING_DELIMITER; } - let occurences = { + const occurences = { single: 0, double: 0 }; @@ -109,10 +109,10 @@ function findCommonStringDelimiter(code, tokens) { let checked = 0; for (let i = 0; i < tokens.length; i++) { - let token = tokens[i]; + const token = tokens[i]; if (token.type.label !== "string") continue; - let raw = code.slice(token.start, token.end); + const raw = code.slice(token.start, token.end); if (raw[0] === "'") { occurences.single++; } else { @@ -145,6 +145,6 @@ export class CodeGenerator { } export default function (ast: Object, opts: Object, code: string): Object { - let gen = new Generator(ast, opts, code); + const gen = new Generator(ast, opts, code); return gen.generate(); } diff --git a/packages/babel-generator/src/node/index.js b/packages/babel-generator/src/node/index.js index 971f478a3da5..c885f8032bd3 100644 --- a/packages/babel-generator/src/node/index.js +++ b/packages/babel-generator/src/node/index.js @@ -3,22 +3,22 @@ import * as parens from "./parentheses"; import * as t from "babel-types"; function expandAliases(obj) { - let newObj = {}; + const newObj = {}; function add(type, func) { - let fn = newObj[type]; + const fn = newObj[type]; newObj[type] = fn ? function(node, parent, stack) { - let result = fn(node, parent, stack); + const result = fn(node, parent, stack); return result == null ? func(node, parent, stack) : result; } : func; } - for (let type of Object.keys(obj)) { + for (const type of Object.keys(obj)) { - let aliases = t.FLIPPED_ALIAS_KEYS[type]; + const aliases = t.FLIPPED_ALIAS_KEYS[type]; if (aliases) { - for (let alias of aliases) { + for (const alias of aliases) { add(alias, obj[type]); } } else { @@ -31,12 +31,12 @@ function expandAliases(obj) { // Rather than using `t.is` on each object property, we pre-expand any type aliases // into concrete types so that the 'find' call below can be as fast as possible. -let expandedParens = expandAliases(parens); -let expandedWhitespaceNodes = expandAliases(whitespace.nodes); -let expandedWhitespaceList = expandAliases(whitespace.list); +const expandedParens = expandAliases(parens); +const expandedWhitespaceNodes = expandAliases(whitespace.nodes); +const expandedWhitespaceList = expandAliases(whitespace.list); function find(obj, node, parent, printStack) { - let fn = obj[node.type]; + const fn = obj[node.type]; return fn ? fn(node, parent, printStack) : null; } @@ -63,7 +63,7 @@ export function needsWhitespace(node, parent, type) { let linesInfo = find(expandedWhitespaceNodes, node, parent); if (!linesInfo) { - let items = find(expandedWhitespaceList, node, parent); + const items = find(expandedWhitespaceList, node, parent); if (items) { for (let i = 0; i < items.length; i++) { linesInfo = needsWhitespace(items[i], node, type); diff --git a/packages/babel-generator/src/node/parentheses.js b/packages/babel-generator/src/node/parentheses.js index 199252d96e90..203ed8a3aa76 100644 --- a/packages/babel-generator/src/node/parentheses.js +++ b/packages/babel-generator/src/node/parentheses.js @@ -60,11 +60,11 @@ export function Binary(node: Object, parent: Object): boolean { } if (t.isBinary(parent)) { - let parentOp = parent.operator; - let parentPos = PRECEDENCE[parentOp]; + const parentOp = parent.operator; + const parentPos = PRECEDENCE[parentOp]; - let nodeOp = node.operator; - let nodePos = PRECEDENCE[nodeOp]; + const nodeOp = node.operator; + const nodePos = PRECEDENCE[nodeOp]; if (parentPos > nodePos) { return true; diff --git a/packages/babel-generator/src/node/whitespace.js b/packages/babel-generator/src/node/whitespace.js index 6ba8522e083b..21320e33d309 100644 --- a/packages/babel-generator/src/node/whitespace.js +++ b/packages/babel-generator/src/node/whitespace.js @@ -69,7 +69,7 @@ exports.nodes = { */ AssignmentExpression(node: Object): ?WhitespaceObject { - let state = crawl(node.right); + const state = crawl(node.right); if ((state.hasCall && state.hasHelper) || state.hasFunction) { return { before: state.hasFunction, @@ -131,11 +131,11 @@ exports.nodes = { VariableDeclaration(node: Object): ?WhitespaceObject { for (let i = 0; i < node.declarations.length; i++) { - let declar = node.declarations[i]; + const declar = node.declarations[i]; let enabled = isHelper(declar.id) && !isType(declar.init); if (!enabled) { - let state = crawl(declar.init); + const state = crawl(declar.init); enabled = (isHelper(declar.init) && state.hasCall) || state.hasFunction; } diff --git a/packages/babel-generator/src/printer.js b/packages/babel-generator/src/printer.js index a9af0094297b..e03298d1f909 100644 --- a/packages/babel-generator/src/printer.js +++ b/packages/babel-generator/src/printer.js @@ -238,7 +238,7 @@ export default class Printer { _maybeAddParen(str: string): void { // see startTerminatorless() instance method - let parenPushNewlineState = this._parenPushNewlineState; + const parenPushNewlineState = this._parenPushNewlineState; if (!parenPushNewlineState) return; this._parenPushNewlineState = null; @@ -314,19 +314,19 @@ export default class Printer { print(node, parent) { if (!node) return; - let oldConcise = this.format.concise; + const oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } - let printMethod = this[node.type]; + const printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`); } this._printStack.push(node); - let oldInAux = this._insideAux; + const oldInAux = this._insideAux; this._insideAux = !node.loc; this._maybeAddAuxComment(this._insideAux && !oldInAux); @@ -340,7 +340,7 @@ export default class Printer { this._printLeadingComments(node, parent); - let loc = (t.isProgram(node) || t.isFile(node)) ? null : node.loc; + const loc = (t.isProgram(node) || t.isFile(node)) ? null : node.loc; this.withSource("start", loc, () => { this[node.type](node, parent); }); @@ -388,7 +388,7 @@ export default class Printer { } getPossibleRaw(node) { - let extra = node.extra; + const extra = node.extra; if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { return extra.raw; } @@ -426,14 +426,14 @@ export default class Printer { } printAndIndentOnComments(node, parent) { - let indent = !!node.leadingComments; + const indent = !!node.leadingComments; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); } printBlock(parent) { - let node = parent.body; + const node = parent.body; if (!t.isEmptyStatement(node)) { this.space(); @@ -544,13 +544,13 @@ export default class Printer { // if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { - let offset = comment.loc && comment.loc.start.column; + const offset = comment.loc && comment.loc.start.column; if (offset) { - let newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } - let indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); + const indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); val = val.replace(/\n(?!$)/g, `\n${repeat(" ", indentSize)}`); } @@ -567,7 +567,7 @@ export default class Printer { _printComments(comments?: Array) { if (!comments || !comments.length) return; - for (let comment of comments) { + for (const comment of comments) { this._printComment(comment); } } @@ -578,7 +578,7 @@ function commaSeparator() { this.space(); } -for (let generator of [ +for (const generator of [ require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), diff --git a/packages/babel-generator/src/whitespace.js b/packages/babel-generator/src/whitespace.js index 2eb4f9b308e3..6a055e02e265 100644 --- a/packages/babel-generator/src/whitespace.js +++ b/packages/babel-generator/src/whitespace.js @@ -15,7 +15,7 @@ export default class Whitespace { getNewlinesBefore(node) { let startToken; let endToken; - let tokens = this.tokens; + const tokens = this.tokens; let index = this._findToken((token) => token.start - node.start, 0, tokens.length); if (index >= 0) { @@ -34,7 +34,7 @@ export default class Whitespace { getNewlinesAfter(node) { let startToken; let endToken; - let tokens = this.tokens; + const tokens = this.tokens; let index = this._findToken((token) => token.end - node.end, 0, tokens.length); if (index >= 0) { @@ -58,8 +58,8 @@ export default class Whitespace { _getNewlinesBetween(startToken, endToken) { if (!endToken || !endToken.loc) return 0; - let start = startToken ? startToken.loc.end.line : 1; - let end = endToken.loc.start.line; + const start = startToken ? startToken.loc.end.line : 1; + const end = endToken.loc.start.line; let lines = 0; for (let line = start; line < end; line++) { diff --git a/packages/babel-generator/test/index.js b/packages/babel-generator/test/index.js index 40d8402d347e..cd84698ba57d 100644 --- a/packages/babel-generator/test/index.js +++ b/packages/babel-generator/test/index.js @@ -1,13 +1,13 @@ -let Whitespace = require("../lib/whitespace"); -let Printer = require("../lib/printer"); -let generate = require("../lib"); -let assert = require("assert"); -let parse = require("babylon").parse; -let chai = require("chai"); -let t = require("babel-types"); -let _ = require("lodash"); -let fs = require("fs"); -let path = require("path"); +const Whitespace = require("../lib/whitespace"); +const Printer = require("../lib/printer"); +const generate = require("../lib"); +const assert = require("assert"); +const parse = require("babylon").parse; +const chai = require("chai"); +const t = require("babel-types"); +const _ = require("lodash"); +const fs = require("fs"); +const path = require("path"); describe("generation", function () { it("completeness", function () { @@ -22,16 +22,16 @@ describe("generation", function () { }); it("multiple sources", function () { - let sources = { + const sources = { "a.js": "function hi (msg) { console.log(msg); }\n", "b.js": "hi('hello');\n" }; - let parsed = _.keys(sources).reduce(function (_parsed, filename) { + const parsed = _.keys(sources).reduce(function (_parsed, filename) { _parsed[filename] = parse(sources[filename], { sourceFilename: filename }); return _parsed; }, {}); - let combinedAst = { + const combinedAst = { "type": "File", "program": { "type": "Program", @@ -40,7 +40,7 @@ describe("generation", function () { } }; - let generated = generate.default(combinedAst, { sourceMaps: true }, sources); + const generated = generate.default(combinedAst, { sourceMaps: true }, sources); chai.expect(generated.map).to.deep.equal({ version: 3, @@ -128,20 +128,20 @@ describe("generation", function () { }); it("identifierName", function () { - let code = "function foo() { bar; }\n"; + const code = "function foo() { bar; }\n"; - let ast = parse(code, { filename: "inline" }).program; - let fn = ast.body[0]; + const ast = parse(code, { filename: "inline" }).program; + const fn = ast.body[0]; - let id = fn.id; + const id = fn.id; id.name += "2"; id.loc.identifierName = "foo"; - let id2 = fn.body.body[0].expression; + const id2 = fn.body.body[0].expression; id2.name += "2"; id2.loc.identiferName = "bar"; - let generated = generate.default(ast, { + const generated = generate.default(ast, { filename: "inline", sourceFileName: "inline", sourceMaps: true @@ -189,10 +189,10 @@ describe("generation", function () { }); it("lazy source map generation", function() { - let code = "function hi (msg) { console.log(msg); }\n"; + const code = "function hi (msg) { console.log(msg); }\n"; - let ast = parse(code, { filename: "a.js" }).program; - let generated = generate.default(ast, { + const ast = parse(code, { filename: "a.js" }).program; + const generated = generate.default(ast, { sourceFileName: "a.js", sourceMaps: true, }); @@ -209,12 +209,12 @@ describe("generation", function () { describe("programmatic generation", function() { it("numeric member expression", function() { // Should not generate `0.foo` - let mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo")); + const mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo")); new Function(generate.default(mem).code); }); it("nested if statements needs block", function() { - let ifStatement = t.ifStatement( + const ifStatement = t.ifStatement( t.stringLiteral("top cond"), t.whileStatement( t.stringLiteral("while cond"), @@ -226,17 +226,17 @@ describe("programmatic generation", function() { t.expressionStatement(t.stringLiteral("alt")) ); - let ast = parse(generate.default(ifStatement).code); + const ast = parse(generate.default(ifStatement).code); assert.equal(ast.program.body[0].consequent.type, "BlockStatement"); }); it("prints directives in block with empty body", function() { - let blockStatement = t.blockStatement( + const blockStatement = t.blockStatement( [], [t.directive(t.directiveLiteral("use strict"))] ); - let output = generate.default(blockStatement).code; + const output = generate.default(blockStatement).code; assert.equal(output, [ "{", " \"use strict\";", @@ -245,7 +245,7 @@ describe("programmatic generation", function() { }); it("flow object indentation", function() { - let objectStatement = t.objectTypeAnnotation( + const objectStatement = t.objectTypeAnnotation( [ t.objectTypeProperty( t.identifier("bar"), @@ -256,7 +256,7 @@ describe("programmatic generation", function() { null ); - let output = generate.default(objectStatement).code; + const output = generate.default(objectStatement).code; assert.equal(output, [ "{", " bar: string;", @@ -265,7 +265,7 @@ describe("programmatic generation", function() { }); it("flow object indentation with empty leading ObjectTypeProperty", function() { - let objectStatement = t.objectTypeAnnotation( + const objectStatement = t.objectTypeAnnotation( [], [ t.objectTypeIndexer( @@ -276,7 +276,7 @@ describe("programmatic generation", function() { ] ); - let output = generate.default(objectStatement).code; + const output = generate.default(objectStatement).code; assert.equal(output, [ "{", @@ -288,29 +288,29 @@ describe("programmatic generation", function() { describe("whitespace", function () { it("empty token list", function () { - let w = new Whitespace([]); + const w = new Whitespace([]); assert.equal(w.getNewlinesBefore(t.stringLiteral("1")), 0); }); }); -let suites = require("babel-helper-fixtures").default(__dirname + "/fixtures"); +const suites = require("babel-helper-fixtures").default(__dirname + "/fixtures"); suites.forEach(function (testSuite) { describe("generation/" + testSuite.title, function () { _.each(testSuite.tests, function (task) { it(task.title, !task.disabled && function () { - let expect = task.expect; - let actual = task.actual; - let actualCode = actual.code; + const expect = task.expect; + const actual = task.actual; + const actualCode = actual.code; if (actualCode) { - let actualAst = parse(actualCode, { + const actualAst = parse(actualCode, { filename: actual.loc, plugins: ["*"], strictMode: false, sourceType: "module", }); - let result = generate.default(actualAst, task.options, actualCode); + const result = generate.default(actualAst, task.options, actualCode); if (!expect.code && result.code && fs.statSync(path.dirname(expect.loc)).isDirectory() && !process.env.CI) { console.log(`New test file created: ${expect.loc}`); diff --git a/packages/babel-helper-bindify-decorators/src/index.js b/packages/babel-helper-bindify-decorators/src/index.js index 750c00f56fdf..debc145a4f04 100644 --- a/packages/babel-helper-bindify-decorators/src/index.js +++ b/packages/babel-helper-bindify-decorators/src/index.js @@ -2,15 +2,15 @@ import type { NodePath } from "babel-traverse"; import * as t from "babel-types"; export default function bindifyDecorators(decorators: Array): Array { - for (let decoratorPath of decorators) { - let decorator = decoratorPath.node; - let expression = decorator.expression; + for (const decoratorPath of decorators) { + const decorator = decoratorPath.node; + const expression = decorator.expression; if (!t.isMemberExpression(expression)) continue; - let temp = decoratorPath.scope.maybeGenerateMemoised(expression.object); + const temp = decoratorPath.scope.maybeGenerateMemoised(expression.object); let ref; - let nodes = []; + const nodes = []; if (temp) { ref = temp; diff --git a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js index 0c07eecf9ff2..b3e41d9f7ed3 100644 --- a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js +++ b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js @@ -5,7 +5,7 @@ export default function (opts: { build: Function; operator: string; }): Object { - let visitor = {}; + const visitor = {}; function isAssignment(node) { return node && node.operator === opts.operator + "="; @@ -19,11 +19,11 @@ export default function (opts: { // hit the `AssignmentExpression` one below if (path.isCompletionRecord()) return; - let expr = path.node.expression; + const expr = path.node.expression; if (!isAssignment(expr)) return; - let nodes = []; - let exploded = explode(expr.left, nodes, file, path.scope, true); + const nodes = []; + const exploded = explode(expr.left, nodes, file, path.scope, true); nodes.push(t.expressionStatement( buildAssignment(exploded.ref, opts.build(exploded.uid, expr.right)) @@ -33,17 +33,17 @@ export default function (opts: { }; visitor.AssignmentExpression = function (path, file) { - let { node, scope } = path; + const { node, scope } = path; if (!isAssignment(node)) return; - let nodes = []; - let exploded = explode(node.left, nodes, file, scope); + const nodes = []; + const exploded = explode(node.left, nodes, file, scope); nodes.push(buildAssignment(exploded.ref, opts.build(exploded.uid, node.right))); path.replaceWithMultiple(nodes); }; visitor.BinaryExpression = function (path) { - let { node } = path; + const { node } = path; if (node.operator === opts.operator) { path.replaceWith(opts.build(node.left, node.right)); } diff --git a/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js b/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js index bf8f9d48b952..335f2e50fa91 100644 --- a/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js +++ b/packages/babel-helper-builder-conditional-assignment-operator-visitor/src/index.js @@ -8,7 +8,7 @@ export default function ( is: Function; }, ) { - let buildAssignment = function (left, right) { + const buildAssignment = function (left, right) { return t.assignmentExpression("=", left, right); }; @@ -16,12 +16,12 @@ export default function ( // hit the `AssignmentExpression` one below if (path.isCompletionRecord()) return; - let expr = path.node.expression; + const expr = path.node.expression; if (!opts.is(expr, file)) return; - let nodes = []; + const nodes = []; - let exploded = explode(expr.left, nodes, file, path.scope); + const exploded = explode(expr.left, nodes, file, path.scope); nodes.push(t.ifStatement( opts.build(exploded.uid, file), @@ -32,11 +32,11 @@ export default function ( }; exports.AssignmentExpression = function (path, file) { - let node = path.node; + const node = path.node; if (!opts.is(node, file)) return; - let nodes = []; - let exploded = explode(node.left, nodes, file, path.scope); + const nodes = []; + const exploded = explode(node.left, nodes, file, path.scope); nodes.push(t.logicalExpression( "&&", diff --git a/packages/babel-helper-builder-react-jsx/src/index.js b/packages/babel-helper-builder-react-jsx/src/index.js index 2438070df0d7..1a0a1ca62632 100644 --- a/packages/babel-helper-builder-react-jsx/src/index.js +++ b/packages/babel-helper-builder-react-jsx/src/index.js @@ -11,7 +11,7 @@ type ElementState = { }; export default function (opts) { - let visitor = {}; + const visitor = {}; visitor.JSXNamespacedName = function (path) { throw path.buildCodeFrameError("Namespace tags are not supported. ReactJSX is not XML."); @@ -19,7 +19,7 @@ export default function (opts) { visitor.JSXElement = { exit(path, file) { - let callExpr = buildElementCall(path.get("openingElement"), file); + const callExpr = buildElementCall(path.get("openingElement"), file); callExpr.arguments = callExpr.arguments.concat(path.node.children); @@ -61,7 +61,7 @@ export default function (opts) { } function convertAttribute(node) { - let value = convertAttributeValue(node.value || t.booleanLiteral(true)); + const value = convertAttributeValue(node.value || t.booleanLiteral(true)); if (t.isStringLiteral(value) && !t.isJSXExpressionContainer(node.value)) { value.value = value.value.replace(/\n\s+/g, " "); @@ -79,8 +79,8 @@ export default function (opts) { function buildElementCall(path, file) { path.parent.children = t.react.buildChildren(path.parent); - let tagExpr = convertJSXIdentifier(path.node.name, path.node); - let args = []; + const tagExpr = convertJSXIdentifier(path.node.name, path.node); + const args = []; let tagName; if (t.isIdentifier(tagExpr)) { @@ -89,7 +89,7 @@ export default function (opts) { tagName = tagExpr.value; } - let state: ElementState = { + const state: ElementState = { tagExpr: tagExpr, tagName: tagName, args: args @@ -124,9 +124,9 @@ export default function (opts) { function buildOpeningElementAttributes(attribs, file) { let _props = []; - let objs = []; + const objs = []; - let useBuiltIns = file.opts.useBuiltIns || false; + const useBuiltIns = file.opts.useBuiltIns || false; if (typeof useBuiltIns !== "boolean") { throw new Error("transform-react-jsx currently only accepts a boolean option for useBuiltIns (defaults to false)"); } @@ -139,7 +139,7 @@ export default function (opts) { } while (attribs.length) { - let prop = attribs.shift(); + const prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); diff --git a/packages/babel-helper-call-delegate/src/index.js b/packages/babel-helper-call-delegate/src/index.js index 1319a662fccc..653a48b172f5 100644 --- a/packages/babel-helper-call-delegate/src/index.js +++ b/packages/babel-helper-call-delegate/src/index.js @@ -2,7 +2,7 @@ import hoistVariables from "babel-helper-hoist-variables"; import type { NodePath } from "babel-traverse"; import * as t from "babel-types"; -let visitor = { +const visitor = { enter(path, state) { if (path.isThisExpression()) { state.foundThis = true; @@ -19,8 +19,8 @@ let visitor = { }; export default function (path: NodePath, scope = path.scope) { - let { node } = path; - let container = t.functionExpression(null, [], node.body, node.generator, node.async); + const { node } = path; + const container = t.functionExpression(null, [], node.body, node.generator, node.async); let callee = container; let args = []; @@ -28,7 +28,7 @@ export default function (path: NodePath, scope = path.scope) { // todo: only hoist if necessary hoistVariables(path, (id) => scope.push({ id })); - let state = { + const state = { foundThis: false, foundArguments: false }; diff --git a/packages/babel-helper-define-map/src/index.js b/packages/babel-helper-define-map/src/index.js index 653674755507..09de4f9b5821 100644 --- a/packages/babel-helper-define-map/src/index.js +++ b/packages/babel-helper-define-map/src/index.js @@ -16,7 +16,7 @@ function toKind(node: Object) { } export function push(mutatorMap: Object, node: Object, kind: string, file, scope?): Object { - let alias = t.toKeyAlias(node); + const alias = t.toKeyAlias(node); // @@ -36,7 +36,7 @@ export function push(mutatorMap: Object, node: Object, kind: string, file, scope } if (node.decorators) { - let decorators = map.decorators = map.decorators || t.arrayExpression([]); + const decorators = map.decorators = map.decorators || t.arrayExpression([]); decorators.elements = decorators.elements.concat(node.decorators.map((dec) => dec.expression).reverse()); } @@ -58,7 +58,7 @@ export function push(mutatorMap: Object, node: Object, kind: string, file, scope value.returnType = node.returnType; } - let inheritedKind = toKind(node); + const inheritedKind = toKind(node); if (!kind || inheritedKind !== "value") { kind = inheritedKind; } @@ -77,7 +77,7 @@ export function push(mutatorMap: Object, node: Object, kind: string, file, scope } export function hasComputed(mutatorMap: Object): boolean { - for (let key in mutatorMap) { + for (const key in mutatorMap) { if (mutatorMap[key]._computed) { return true; } @@ -86,11 +86,11 @@ export function hasComputed(mutatorMap: Object): boolean { } export function toComputedObjectFromClass(obj: Object): Object { - let objExpr = t.arrayExpression([]); + const objExpr = t.arrayExpression([]); for (let i = 0; i < obj.properties.length; i++) { - let prop = obj.properties[i]; - let val = prop.value; + const prop = obj.properties[i]; + const val = prop.value; val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); objExpr.elements.push(val); } @@ -99,20 +99,20 @@ export function toComputedObjectFromClass(obj: Object): Object { } export function toClassObject(mutatorMap: Object): Object { - let objExpr = t.objectExpression([]); + const objExpr = t.objectExpression([]); each(mutatorMap, function (map) { - let mapNode = t.objectExpression([]); + const mapNode = t.objectExpression([]); - let propNode = t.objectProperty(map._key, mapNode, map._computed); + const propNode = t.objectProperty(map._key, mapNode, map._computed); each(map, function (node, key) { if (key[0] === "_") return; - let inheritNode = node; + const inheritNode = node; if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; - let prop = t.objectProperty(t.identifier(key), node); + const prop = t.objectProperty(t.identifier(key), node); t.inheritsComments(prop, inheritNode); t.removeComments(inheritNode); diff --git a/packages/babel-helper-explode-assignable-expression/src/index.js b/packages/babel-helper-explode-assignable-expression/src/index.js index 8ffdd95fa201..04052f5e3403 100644 --- a/packages/babel-helper-explode-assignable-expression/src/index.js +++ b/packages/babel-helper-explode-assignable-expression/src/index.js @@ -31,7 +31,7 @@ function getObjRef(node, nodes, file, scope) { throw new Error(`We can't explode this node type ${node.type}`); } - let temp = scope.generateUidIdentifierBasedOnNode(ref); + const temp = scope.generateUidIdentifierBasedOnNode(ref); nodes.push(t.variableDeclaration("var", [ t.variableDeclarator(temp, ref) ])); @@ -39,11 +39,11 @@ function getObjRef(node, nodes, file, scope) { } function getPropRef(node, nodes, file, scope) { - let prop = node.property; - let key = t.toComputedKey(node, prop); + const prop = node.property; + const key = t.toComputedKey(node, prop); if (t.isLiteral(key) && t.isPureish(key)) return key; - let temp = scope.generateUidIdentifierBasedOnNode(prop); + const temp = scope.generateUidIdentifierBasedOnNode(prop); nodes.push(t.variableDeclaration("var", [ t.variableDeclarator(temp, prop) ])); @@ -73,8 +73,8 @@ export default function ( ref = node; uid = obj; } else { - let prop = getPropRef(node, nodes, file, scope); - let computed = node.computed || t.isLiteral(prop); + const prop = getPropRef(node, nodes, file, scope); + const computed = node.computed || t.isLiteral(prop); uid = ref = t.memberExpression(obj, prop, computed); } diff --git a/packages/babel-helper-explode-class/src/index.js b/packages/babel-helper-explode-class/src/index.js index 1091e1ba0638..2ced5be5b179 100644 --- a/packages/babel-helper-explode-class/src/index.js +++ b/packages/babel-helper-explode-class/src/index.js @@ -5,12 +5,12 @@ import * as t from "babel-types"; export default function (classPath) { classPath.assertClass(); - let memoisedExpressions = []; + const memoisedExpressions = []; function maybeMemoise(path) { if (!path.node || path.isPure()) return; - let uid = classPath.scope.generateDeclaredUidIdentifier(); + const uid = classPath.scope.generateDeclaredUidIdentifier(); memoisedExpressions.push(t.assignmentExpression("=", uid, path.node)); path.replaceWith(uid); } @@ -24,7 +24,7 @@ export default function (classPath) { // bind decorators if they're member expressions bindifyDecorators(paths); - for (let path of paths) { + for (const path of paths) { maybeMemoise(path); } } @@ -32,8 +32,8 @@ export default function (classPath) { maybeMemoise(classPath.get("superClass")); memoiseDecorators(classPath.get("decorators"), true); - let methods: Array = classPath.get("body.body"); - for (let methodPath of methods) { + const methods: Array = classPath.get("body.body"); + for (const methodPath of methods) { if (methodPath.is("computed")) { maybeMemoise(methodPath.get("key")); } diff --git a/packages/babel-helper-fixtures/src/index.js b/packages/babel-helper-fixtures/src/index.js index 40faaf153037..e7fcebf1d95e 100644 --- a/packages/babel-helper-fixtures/src/index.js +++ b/packages/babel-helper-fixtures/src/index.js @@ -41,23 +41,23 @@ function shouldIgnore(name, blacklist?: Array) { return true; } - let ext = path.extname(name); - let base = path.basename(name, ext); + const ext = path.extname(name); + const base = path.basename(name, ext); return name[0] === "." || ext === ".md" || base === "LICENSE" || base === "options"; } export default function get(entryLoc): Array { - let suites = []; + const suites = []; let rootOpts = {}; - let rootOptsLoc = resolve(entryLoc + "/options"); + const rootOptsLoc = resolve(entryLoc + "/options"); if (rootOptsLoc) rootOpts = require(rootOptsLoc); - for (let suiteName of fs.readdirSync(entryLoc)) { + for (const suiteName of fs.readdirSync(entryLoc)) { if (shouldIgnore(suiteName)) continue; - let suite = { + const suite = { options: _.clone(rootOpts), tests: [], title: humanize(suiteName), @@ -67,24 +67,24 @@ export default function get(entryLoc): Array { assertDirectory(suite.filename); suites.push(suite); - let suiteOptsLoc = resolve(suite.filename + "/options"); + const suiteOptsLoc = resolve(suite.filename + "/options"); if (suiteOptsLoc) suite.options = require(suiteOptsLoc); - for (let taskName of fs.readdirSync(suite.filename)) { + for (const taskName of fs.readdirSync(suite.filename)) { push(taskName, suite.filename + "/" + taskName); } function push(taskName, taskDir) { - let actualLocAlias = suiteName + "/" + taskName + "/actual.js"; + const actualLocAlias = suiteName + "/" + taskName + "/actual.js"; let expectLocAlias = suiteName + "/" + taskName + "/expected.js"; - let execLocAlias = suiteName + "/" + taskName + "/exec.js"; + const execLocAlias = suiteName + "/" + taskName + "/exec.js"; - let actualLoc = taskDir + "/actual.js"; + const actualLoc = taskDir + "/actual.js"; let expectLoc = taskDir + "/expected.js"; let execLoc = taskDir + "/exec.js"; if (fs.statSync(taskDir).isFile()) { - let ext = path.extname(taskDir); + const ext = path.extname(taskDir); if (ext !== ".js" && ext !== ".module.js") return; execLoc = taskDir; @@ -95,12 +95,12 @@ export default function get(entryLoc): Array { expectLocAlias += "on"; } - let taskOpts = _.cloneDeep(suite.options); + const taskOpts = _.cloneDeep(suite.options); - let taskOptsLoc = resolve(taskDir + "/options"); + const taskOptsLoc = resolve(taskDir + "/options"); if (taskOptsLoc) _.merge(taskOpts, require(taskOptsLoc)); - let test = { + const test = { optionsDir: taskOptsLoc ? path.dirname(taskOptsLoc) : null, title: humanize(taskName, true), disabled: taskName[0] === ".", @@ -130,12 +130,12 @@ export default function get(entryLoc): Array { suite.tests.push(test); - let sourceMappingsLoc = taskDir + "/source-mappings.json"; + const sourceMappingsLoc = taskDir + "/source-mappings.json"; if (fs.existsSync(sourceMappingsLoc)) { test.sourceMappings = JSON.parse(readFile(sourceMappingsLoc)); } - let sourceMapLoc = taskDir + "/source-map.json"; + const sourceMapLoc = taskDir + "/source-map.json"; if (fs.existsSync(sourceMapLoc)) { test.sourceMap = JSON.parse(readFile(sourceMapLoc)); } @@ -146,12 +146,12 @@ export default function get(entryLoc): Array { } export function multiple(entryLoc, ignore?: Array) { - let categories = {}; + const categories = {}; - for (let name of fs.readdirSync(entryLoc)) { + for (const name of fs.readdirSync(entryLoc)) { if (shouldIgnore(name, ignore)) continue; - let loc = path.join(entryLoc, name); + const loc = path.join(entryLoc, name); assertDirectory(loc); categories[name] = get(loc); diff --git a/packages/babel-helper-function-name/src/index.js b/packages/babel-helper-function-name/src/index.js index 1e6d8add9d31..7623bf0a10b0 100644 --- a/packages/babel-helper-function-name/src/index.js +++ b/packages/babel-helper-function-name/src/index.js @@ -4,7 +4,7 @@ import getFunctionArity from "babel-helper-get-function-arity"; import template from "babel-template"; import * as t from "babel-types"; -let buildPropertyMethodAssignmentWrapper = template(` +const buildPropertyMethodAssignmentWrapper = template(` (function (FUNCTION_KEY) { function FUNCTION_ID() { return FUNCTION_KEY.apply(this, arguments); @@ -18,7 +18,7 @@ let buildPropertyMethodAssignmentWrapper = template(` })(FUNCTION) `); -let buildGeneratorPropertyMethodAssignmentWrapper = template(` +const buildGeneratorPropertyMethodAssignmentWrapper = template(` (function (FUNCTION_KEY) { function* FUNCTION_ID() { return yield* FUNCTION_KEY.apply(this, arguments); @@ -32,14 +32,14 @@ let buildGeneratorPropertyMethodAssignmentWrapper = template(` })(FUNCTION) `); -let visitor = { +const visitor = { "ReferencedIdentifier|BindingIdentifier"(path, state) { // check if this node matches our function id if (path.node.name !== state.name) return; // check that we don't have a local variable declared as that removes the need // for the wrapper - let localDeclar = path.scope.getBindingIdentifier(state.name); + const localDeclar = path.scope.getBindingIdentifier(state.name); if (localDeclar !== state.outerDeclar) return; state.selfReference = true; @@ -59,7 +59,7 @@ function wrap(state, method, id, scope) { // need to add a wrapper since we can't change the references let build = buildPropertyMethodAssignmentWrapper; if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; - let template = build({ + const template = build({ FUNCTION: method, FUNCTION_ID: id, FUNCTION_KEY: scope.generateUidIdentifier(id.name) @@ -68,7 +68,7 @@ function wrap(state, method, id, scope) { // shim in dummy params to retain function arity, if you try to read the // source then you'll get the original since it's proxied so it's all good - let params = template.callee.body.body[0].params; + const params = template.callee.body.body[0].params; for (let i = 0, len = getFunctionArity(method); i < len; i++) { params.push(scope.generateUidIdentifier("x")); } @@ -82,7 +82,7 @@ function wrap(state, method, id, scope) { } function visit(node, name, scope) { - let state = { + const state = { selfAssignment: false, selfReference: false, outerDeclar: scope.getBindingIdentifier(name), @@ -93,7 +93,7 @@ function visit(node, name, scope) { // check to see if we have a local binding of the id we're setting inside of // the function, this is important as there are caveats associated - let binding = scope.getOwnBinding(name); + const binding = scope.getOwnBinding(name); if (binding) { if (binding.kind === "param") { @@ -139,7 +139,7 @@ export default function ({ node, parent, scope, id }) { id = parent.id; if (t.isIdentifier(id)) { - let binding = scope.parent.getBinding(id.name); + const binding = scope.parent.getBinding(id.name); if (binding && binding.constant && scope.getBinding(id.name) === binding) { // always going to reference this method node.id = id; @@ -171,6 +171,6 @@ export default function ({ node, parent, scope, id }) { // a local binding. id[t.NOT_LOCAL_BINDING] = true; - let state = visit(node, name, scope); + const state = visit(node, name, scope); return wrap(state, node, id, scope) || node; } diff --git a/packages/babel-helper-get-function-arity/src/index.js b/packages/babel-helper-get-function-arity/src/index.js index a3c60a5a614d..c54613f6fef3 100644 --- a/packages/babel-helper-get-function-arity/src/index.js +++ b/packages/babel-helper-get-function-arity/src/index.js @@ -1,9 +1,9 @@ import * as t from "babel-types"; export default function (node): number { - let params: Array = node.params; + const params: Array = node.params; for (let i = 0; i < params.length; i++) { - let param = params[i]; + const param = params[i]; if (t.isAssignmentPattern(param) || t.isRestElement(param)) { return i; } diff --git a/packages/babel-helper-hoist-variables/src/index.js b/packages/babel-helper-hoist-variables/src/index.js index de36a3f59197..dafcc98ca8e5 100644 --- a/packages/babel-helper-hoist-variables/src/index.js +++ b/packages/babel-helper-hoist-variables/src/index.js @@ -1,6 +1,6 @@ import * as t from "babel-types"; -let visitor = { +const visitor = { Scope(path, state) { if (state.kind === "let") path.skip(); }, @@ -12,12 +12,12 @@ let visitor = { VariableDeclaration(path, state) { if (state.kind && path.node.kind !== state.kind) return; - let nodes = []; + const nodes = []; - let declarations: Array = path.get("declarations"); + const declarations: Array = path.get("declarations"); let firstId; - for (let declar of declarations) { + for (const declar of declarations) { firstId = declar.node.id; if (declar.node.init) { @@ -26,7 +26,7 @@ let visitor = { )); } - for (let name in declar.getBindingIdentifiers()) { + for (const name in declar.getBindingIdentifiers()) { state.emit(t.identifier(name), name); } } diff --git a/packages/babel-helper-plugin-test-runner/src/index.js b/packages/babel-helper-plugin-test-runner/src/index.js index 749f964aa3da..37bcc4360c9f 100644 --- a/packages/babel-helper-plugin-test-runner/src/index.js +++ b/packages/babel-helper-plugin-test-runner/src/index.js @@ -2,6 +2,6 @@ import testRunner from "babel-helper-transform-fixture-test-runner"; import path from "path"; export default function (loc) { - let name = path.basename(path.dirname(loc)); + const name = path.basename(path.dirname(loc)); testRunner(loc + "/fixtures", name); } diff --git a/packages/babel-helper-regex/src/index.js b/packages/babel-helper-regex/src/index.js index b59a30f7d543..998bbe4716f7 100644 --- a/packages/babel-helper-regex/src/index.js +++ b/packages/babel-helper-regex/src/index.js @@ -6,7 +6,7 @@ export function is(node: Object, flag: string): boolean { } export function pullFlag(node: Object, flag: string) { - let flags = node.flags.split(""); + const flags = node.flags.split(""); if (node.flags.indexOf(flag) < 0) return; pull(flags, flag); node.flags = flags.join(""); diff --git a/packages/babel-helper-remap-async-to-generator/src/for-await.js b/packages/babel-helper-remap-async-to-generator/src/for-await.js index 5e3fe1f0bc24..77b7738b7ca1 100644 --- a/packages/babel-helper-remap-async-to-generator/src/for-await.js +++ b/packages/babel-helper-remap-async-to-generator/src/for-await.js @@ -2,7 +2,7 @@ import * as t from "babel-types"; import template from "babel-template"; import traverse from "babel-traverse"; -let buildForAwait = template(` +const buildForAwait = template(` function* wrapper() { var ITERATOR_COMPLETION = true; var ITERATOR_HAD_ERROR_KEY = false; @@ -35,7 +35,7 @@ let buildForAwait = template(` } `); -let forAwaitVisitor = { +const forAwaitVisitor = { noScope: true, Identifier(path, replacements) { @@ -45,7 +45,7 @@ let forAwaitVisitor = { }, CallExpression(path, replacements) { - let callee = path.node.callee; + const callee = path.node.callee; // if no await wrapping is being applied, unwrap the call expression if (t.isIdentifier(callee) && callee.name === "AWAIT" && !replacements.AWAIT) { @@ -55,11 +55,11 @@ let forAwaitVisitor = { }; export default function (path, helpers) { - let { node, scope, parent } = path; + const { node, scope, parent } = path; - let stepKey = scope.generateUidIdentifier("step"); - let stepValue = scope.generateUidIdentifier("value"); - let left = node.left; + const stepKey = scope.generateUidIdentifier("step"); + const stepValue = scope.generateUidIdentifier("value"); + const left = node.left; let declar; if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { @@ -89,9 +89,9 @@ export default function (path, helpers) { // remove generator function wrapper template = template.body.body; - let isLabeledParent = t.isLabeledStatement(parent); - let tryBody = template[3].block.body; - let loop = tryBody[0]; + const isLabeledParent = t.isLabeledStatement(parent); + const tryBody = template[3].block.body; + const loop = tryBody[0]; if (isLabeledParent) { tryBody[0] = t.labeledStatement(parent.label, loop); diff --git a/packages/babel-helper-remap-async-to-generator/src/index.js b/packages/babel-helper-remap-async-to-generator/src/index.js index 840a195d8afd..deca1eb65087 100644 --- a/packages/babel-helper-remap-async-to-generator/src/index.js +++ b/packages/babel-helper-remap-async-to-generator/src/index.js @@ -6,7 +6,7 @@ import template from "babel-template"; import * as t from "babel-types"; import rewriteForAwait from "./for-await"; -let buildWrapper = template(` +const buildWrapper = template(` (() => { var REF = FUNCTION; return function NAME(PARAMS) { @@ -15,7 +15,7 @@ let buildWrapper = template(` }) `); -let namedBuildWrapper = template(` +const namedBuildWrapper = template(` (() => { var REF = FUNCTION; function NAME(PARAMS) { @@ -25,7 +25,7 @@ let namedBuildWrapper = template(` }) `); -let awaitVisitor = { +const awaitVisitor = { Function(path) { if (path.isArrowFunctionExpression() && !path.node.async) { path.arrowFunctionToShadowed(); @@ -42,15 +42,15 @@ let awaitVisitor = { }, ForAwaitStatement(path, { file, wrapAwait }) { - let { node } = path; + const { node } = path; - let build = rewriteForAwait(path, { + const build = rewriteForAwait(path, { getAsyncIterator: file.addHelper("asyncIterator"), wrapAwait }); - let { declar, loop } = build; - let block = loop.body; + const { declar, loop } = build; + const block = loop.body; // ensure that it's a block so we can take all its statements path.ensureBlock(); @@ -77,12 +77,12 @@ let awaitVisitor = { }; function classOrObjectMethod(path: NodePath, callId: Object) { - let node = path.node; - let body = node.body; + const node = path.node; + const body = node.body; node.async = false; - let container = t.functionExpression(null, [], t.blockStatement(body.body), true); + const container = t.functionExpression(null, [], t.blockStatement(body.body), true); container.shadow = true; body.body = [ t.returnStatement(t.callExpression( @@ -97,9 +97,9 @@ function classOrObjectMethod(path: NodePath, callId: Object) { } function plainFunction(path: NodePath, callId: Object) { - let node = path.node; - let isDeclaration = path.isFunctionDeclaration(); - let asyncFnId = node.id; + const node = path.node; + const isDeclaration = path.isFunctionDeclaration(); + const asyncFnId = node.id; let wrapper = buildWrapper; if (path.isArrowFunctionExpression()) { @@ -117,8 +117,8 @@ function plainFunction(path: NodePath, callId: Object) { node.type = "FunctionExpression"; } - let built = t.callExpression(callId, [node]); - let container = wrapper({ + const built = t.callExpression(callId, [node]); + const container = wrapper({ NAME: asyncFnId, REF: path.scope.generateUidIdentifier("ref"), FUNCTION: built, @@ -137,7 +137,7 @@ function plainFunction(path: NodePath, callId: Object) { }).expression; if (isDeclaration) { - let declar = t.variableDeclaration("let", [ + const declar = t.variableDeclaration("let", [ t.variableDeclarator( t.identifier(asyncFnId.name), t.callExpression(container, []) @@ -147,7 +147,7 @@ function plainFunction(path: NodePath, callId: Object) { path.replaceWith(declar); } else { - let retFunction = container.body.body[1].argument; + const retFunction = container.body.body[1].argument; if (!asyncFnId) { nameFunction({ node: retFunction, diff --git a/packages/babel-helper-replace-supers/src/index.js b/packages/babel-helper-replace-supers/src/index.js index 8465df19361c..821475355213 100644 --- a/packages/babel-helper-replace-supers/src/index.js +++ b/packages/babel-helper-replace-supers/src/index.js @@ -6,7 +6,7 @@ import * as messages from "babel-messages"; import * as t from "babel-types"; // ✌️ -let HARDCORE_THIS_REF = Symbol(); +const HARDCORE_THIS_REF = Symbol(); function isIllegalBareSuper(node, parent) { if (!t.isSuper(node)) return false; @@ -46,7 +46,7 @@ function getPrototypeOfExpression(objectRef, isStatic) { ); } -let visitor = { +const visitor = { Function(path) { if (!path.inShadow("this")) { path.skip(); @@ -69,9 +69,9 @@ let visitor = { let callback = state.specHandle; if (state.isLoose) callback = state.looseHandle; - let isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); + const isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); - let result = callback.call(state, path); + const result = callback.call(state, path); if (result) { state.hasSuper = true; @@ -185,8 +185,8 @@ export default class ReplaceSupers { } getLooseSuperProperty(id: Object, parent: Object) { - let methodNode = this.methodNode; - let superRef = this.superRef || t.identifier("Function"); + const methodNode = this.methodNode; + const superRef = this.superRef || t.identifier("Function"); if (parent.property === id) { return; @@ -201,11 +201,11 @@ export default class ReplaceSupers { } looseHandle(path: NodePath) { - let node = path.node; + const node = path.node; if (path.isSuper()) { return this.getLooseSuperProperty(node, path.parent); } else if (path.isCallExpression()) { - let callee = node.callee; + const callee = node.callee; if (!t.isMemberExpression(callee)) return; if (!t.isSuper(callee.object)) return; @@ -239,15 +239,15 @@ export default class ReplaceSupers { let computed; let args; - let parent = path.parent; - let node = path.node; + const parent = path.parent; + const node = path.node; if (isIllegalBareSuper(node, parent)) { throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); } if (t.isCallExpression(node)) { - let callee = node.callee; + const callee = node.callee; if (t.isSuper(callee)) { return; } else if (isMemberExpressionSuper(callee)) { @@ -261,13 +261,13 @@ export default class ReplaceSupers { property = node.property; computed = node.computed; } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { - let binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); + const binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); if (node.prefix) { // ++super.foo; -> super.foo += 1; return this.specHandleAssignmentExpression(null, path, binary); } else { // super.foo++; -> let _ref = super.foo; super.foo = _ref + 1; - let ref = path.scope.generateUidIdentifier("ref"); + const ref = path.scope.generateUidIdentifier("ref"); return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); } } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { @@ -276,7 +276,7 @@ export default class ReplaceSupers { if (!property) return; - let superProperty = this.getSuperProperty(property, computed); + const superProperty = this.getSuperProperty(property, computed); if (args) { return this.optimiseCall(superProperty, args); @@ -286,7 +286,7 @@ export default class ReplaceSupers { } optimiseCall(callee, args) { - let thisNode = t.thisExpression(); + const thisNode = t.thisExpression(); thisNode[HARDCORE_THIS_REF] = true; return optimiseCall(callee, thisNode, args); } diff --git a/packages/babel-helper-transform-fixture-test-runner/src/helpers.js b/packages/babel-helper-transform-fixture-test-runner/src/helpers.js index bd4a61d3b986..f28904263838 100644 --- a/packages/babel-helper-transform-fixture-test-runner/src/helpers.js +++ b/packages/babel-helper-transform-fixture-test-runner/src/helpers.js @@ -16,4 +16,4 @@ export function multiline(arr) { return arr.join("\n"); } -export let assertArrayEquals = assert.deepEqual; +export const assertArrayEquals = assert.deepEqual; diff --git a/packages/babel-helper-transform-fixture-test-runner/src/index.js b/packages/babel-helper-transform-fixture-test-runner/src/index.js index 9fced3069fae..11220e77ff19 100644 --- a/packages/babel-helper-transform-fixture-test-runner/src/index.js +++ b/packages/babel-helper-transform-fixture-test-runner/src/index.js @@ -11,7 +11,7 @@ import "babel-polyfill"; import fs from "fs"; import path from "path"; -let babelHelpers = eval(buildExternalHelpers(null, "var")); +const babelHelpers = eval(buildExternalHelpers(null, "var")); function wrapPackagesArray(type, names, optionsDir) { return (names || []).map(function (val) { @@ -36,14 +36,14 @@ function wrapPackagesArray(type, names, optionsDir) { } function run(task) { - let actual = task.actual; - let expect = task.expect; - let exec = task.exec; - let opts = task.options; - let optionsDir = task.optionsDir; + const actual = task.actual; + const expect = task.expect; + const exec = task.exec; + const opts = task.options; + const optionsDir = task.optionsDir; function getOpts(self) { - let newOpts = _.merge({ + const newOpts = _.merge({ filename: self.loc, }, opts); @@ -64,8 +64,8 @@ function run(task) { let resultExec; if (execCode) { - let execOpts = getOpts(exec); - let execDirName = path.dirname(exec.loc); + const execOpts = getOpts(exec); + const execDirName = path.dirname(exec.loc); result = babel.transform(execCode, execOpts); execCode = result.code; @@ -79,7 +79,7 @@ function run(task) { } let actualCode = actual.code; - let expectCode = expect.code; + const expectCode = expect.code; if (!execCode || actualCode) { result = babel.transform(actualCode, getOpts(actual)); if (!expect.code && result.code && !opts.throws && fs.statSync(path.dirname(expect.loc)).isDirectory() && !process.env.CI) { @@ -96,12 +96,12 @@ function run(task) { } if (task.sourceMappings) { - let consumer = new sourceMap.SourceMapConsumer(result.map); + const consumer = new sourceMap.SourceMapConsumer(result.map); _.each(task.sourceMappings, function (mapping) { - let actual = mapping.original; + const actual = mapping.original; - let expect = consumer.originalPositionFor(mapping.generated); + const expect = consumer.originalPositionFor(mapping.generated); chai.expect({ line: expect.line, column: expect.column }).to.deep.equal(actual); }); } @@ -112,7 +112,7 @@ function run(task) { } function runExec(opts, execCode, execDirname) { - let sandbox = { + const sandbox = { ...helpers, babelHelpers, assert: chai.assert, @@ -124,7 +124,7 @@ function runExec(opts, execCode, execDirname) { } }; - let fn = new Function(...Object.keys(sandbox), execCode); + const fn = new Function(...Object.keys(sandbox), execCode); return fn.apply(null, Object.values(sandbox)); } @@ -135,13 +135,13 @@ export default function ( taskOpts = {}, dynamicOpts?: Function, ) { - let suites = getFixtures(fixturesLoc); + const suites = getFixtures(fixturesLoc); - for (let testSuite of suites) { + for (const testSuite of suites) { if (_.includes(suiteOpts.ignoreSuites, testSuite.title)) continue; describe(name + "/" + testSuite.title, function () { - for (let task of testSuite.tests) { + for (const task of testSuite.tests) { if (_.includes(suiteOpts.ignoreTasks, task.title) || _.includes(suiteOpts.ignoreTasks, testSuite.title + "/" + task.title)) continue; @@ -163,7 +163,7 @@ export default function ( if (dynamicOpts) dynamicOpts(task.options, task); - let throwMsg = task.options.throws; + const throwMsg = task.options.throws; if (throwMsg) { // internal api doesn't have this option but it's best not to pollute // the options object with useless options @@ -174,7 +174,7 @@ export default function ( }); } else { if (task.exec.code) { - let result = run(task); + const result = run(task); if (result && typeof result.then === "function") { return result; } diff --git a/packages/babel-helpers/src/helpers.js b/packages/babel-helpers/src/helpers.js index 87a58c3dc957..cdd63768da09 100644 --- a/packages/babel-helpers/src/helpers.js +++ b/packages/babel-helpers/src/helpers.js @@ -2,7 +2,7 @@ import template from "babel-template"; -let helpers = {}; +const helpers = {}; export default helpers; helpers.typeof = template(` diff --git a/packages/babel-helpers/src/index.js b/packages/babel-helpers/src/index.js index e742f224a368..207318cf275b 100644 --- a/packages/babel-helpers/src/index.js +++ b/packages/babel-helpers/src/index.js @@ -3,13 +3,13 @@ import helpers from "./helpers"; export function get(name) { - let fn = helpers[name]; + const fn = helpers[name]; if (!fn) throw new ReferenceError(`Unknown helper ${name}`); return fn().expression; } -export let list = Object.keys(helpers) +export const list = Object.keys(helpers) .map((name) => name[0] === "_" ? name.slice(1) : name) .filter((name) => name !== "__esModule"); diff --git a/packages/babel-messages/src/index.js b/packages/babel-messages/src/index.js index 3fce2e2cf277..7064bd69b920 100644 --- a/packages/babel-messages/src/index.js +++ b/packages/babel-messages/src/index.js @@ -48,7 +48,7 @@ export const MESSAGES = { */ export function get(key: string, ...args: Array): string { - let msg = MESSAGES[key]; + const msg = MESSAGES[key]; if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`); // stringify args diff --git a/packages/babel-plugin-check-es2015-constants/src/index.js b/packages/babel-plugin-check-es2015-constants/src/index.js index 4269b0385c7e..b090052bf59f 100644 --- a/packages/babel-plugin-check-es2015-constants/src/index.js +++ b/packages/babel-plugin-check-es2015-constants/src/index.js @@ -2,11 +2,11 @@ export default function ({ messages }) { return { visitor: { Scope({ scope }) { - for (let name in scope.bindings) { - let binding = scope.bindings[name]; + for (const name in scope.bindings) { + const binding = scope.bindings[name]; if (binding.kind !== "const" && binding.kind !== "module") continue; - for (let violation of (binding.constantViolations: Array)) { + for (const violation of (binding.constantViolations: Array)) { throw violation.buildCodeFrameError(messages.get("readOnly", name)); } } diff --git a/packages/babel-plugin-transform-async-generator-functions/src/index.js b/packages/babel-plugin-transform-async-generator-functions/src/index.js index 409b14f36494..3da5e7d19b81 100644 --- a/packages/babel-plugin-transform-async-generator-functions/src/index.js +++ b/packages/babel-plugin-transform-async-generator-functions/src/index.js @@ -1,14 +1,14 @@ import remapAsyncToGenerator from "babel-helper-remap-async-to-generator"; export default function ({ types: t }) { - let yieldStarVisitor = { + const yieldStarVisitor = { Function(path) { path.skip(); }, YieldExpression({ node }, state) { if (!node.delegate) return; - let callee = state.addHelper("asyncGeneratorDelegate"); + const callee = state.addHelper("asyncGeneratorDelegate"); node.argument = t.callExpression(callee, [ t.callExpression(state.addHelper("asyncIterator"), [node.argument]), t.memberExpression(state.addHelper("asyncGenerator"), t.identifier("await")) diff --git a/packages/babel-plugin-transform-class-constructor-call/src/index.js b/packages/babel-plugin-transform-class-constructor-call/src/index.js index 5d2e80f90f53..09de2b5baa80 100644 --- a/packages/babel-plugin-transform-class-constructor-call/src/index.js +++ b/packages/babel-plugin-transform-class-constructor-call/src/index.js @@ -1,6 +1,6 @@ import template from "babel-template"; -let buildWrapper = template(` +const buildWrapper = template(` let CLASS_REF = CLASS; var CALL_REF = CALL; var WRAPPER_REF = function (...args) { @@ -15,12 +15,12 @@ let buildWrapper = template(` `); export default function ({ types: t }) { - let ALREADY_VISITED = Symbol(); + const ALREADY_VISITED = Symbol(); function findConstructorCall(path): ?Object { - let methods: Array = path.get("body.body"); + const methods: Array = path.get("body.body"); - for (let method of methods) { + for (const method of methods) { if (method.node.kind === "constructorCall") { return method; } @@ -30,8 +30,8 @@ export default function ({ types: t }) { } function handleClassWithCall(constructorCall, classPath) { - let { node } = classPath; - let ref = node.id || classPath.scope.generateUidIdentifier("class"); + const { node } = classPath; + const ref = node.id || classPath.scope.generateUidIdentifier("class"); if (classPath.parentPath.isExportDefaultDeclaration()) { classPath = classPath.parentPath; @@ -57,7 +57,7 @@ export default function ({ types: t }) { if (path.node[ALREADY_VISITED]) return; path.node[ALREADY_VISITED] = true; - let constructorCall = findConstructorCall(path); + const constructorCall = findConstructorCall(path); if (constructorCall) { handleClassWithCall(constructorCall, path); diff --git a/packages/babel-plugin-transform-class-properties/src/index.js b/packages/babel-plugin-transform-class-properties/src/index.js index 10451b377988..af383d44bd1f 100644 --- a/packages/babel-plugin-transform-class-properties/src/index.js +++ b/packages/babel-plugin-transform-class-properties/src/index.js @@ -3,7 +3,7 @@ import nameFunction from "babel-helper-function-name"; import template from "babel-template"; export default function ({ types: t }) { - let findBareSupers = { + const findBareSupers = { Super(path) { if (path.parentPath.isCallExpression({ callee: path.node })) { this.push(path.parentPath); @@ -11,7 +11,7 @@ export default function ({ types: t }) { } }; - let referenceVisitor = { + const referenceVisitor = { ReferencedIdentifier(path) { if (this.scope.hasOwnBinding(path.node.name)) { this.collision = true; @@ -45,12 +45,12 @@ export default function ({ types: t }) { visitor: { Class(path, state) { const buildClassProperty = state.opts.spec ? buildClassPropertySpec : buildClassPropertyNonSpec; - let isDerived = !!path.node.superClass; + const isDerived = !!path.node.superClass; let constructor; - let props = []; - let body = path.get("body"); + const props = []; + const body = path.get("body"); - for (let path of body.get("body")) { + for (const path of body.get("body")) { if (path.isClassProperty()) { props.push(path); } else if (path.isClassMethod({ kind: "constructor" })) { @@ -60,7 +60,7 @@ export default function ({ types: t }) { if (!props.length) return; - let nodes = []; + const nodes = []; let ref; if (path.isClassExpression() || !path.node.id) { @@ -72,15 +72,15 @@ export default function ({ types: t }) { let instanceBody = []; - for (let prop of props) { - let propNode = prop.node; + for (const prop of props) { + const propNode = prop.node; if (propNode.decorators && propNode.decorators.length > 0) continue; // In non-spec mode, all properties without values are ignored. // In spec mode, *static* properties without values are still defined (see below). if (!state.opts.spec && !propNode.value) continue; - let isStatic = propNode.static; + const isStatic = propNode.static; if (isStatic) { nodes.push(buildClassProperty(ref, propNode)); @@ -92,7 +92,7 @@ export default function ({ types: t }) { if (instanceBody.length) { if (!constructor) { - let newConstructor = t.classMethod("constructor", t.identifier("constructor"), [], t.blockStatement([])); + const newConstructor = t.classMethod("constructor", t.identifier("constructor"), [], t.blockStatement([])); if (isDerived) { newConstructor.params = [t.restElement(t.identifier("args"))]; newConstructor.body.body.push( @@ -107,18 +107,18 @@ export default function ({ types: t }) { [constructor] = body.unshiftContainer("body", newConstructor); } - let collisionState = { + const collisionState = { collision: false, scope: constructor.scope }; - for (let prop of props) { + for (const prop of props) { prop.traverse(referenceVisitor, collisionState); if (collisionState.collision) break; } if (collisionState.collision) { - let initialisePropsRef = path.scope.generateUidIdentifier("initialiseProps"); + const initialisePropsRef = path.scope.generateUidIdentifier("initialiseProps"); nodes.push(t.variableDeclaration("var", [ t.variableDeclarator( @@ -137,9 +137,9 @@ export default function ({ types: t }) { // if (isDerived) { - let bareSupers = []; + const bareSupers = []; constructor.traverse(findBareSupers, bareSupers); - for (let bareSuper of bareSupers) { + for (const bareSuper of bareSupers) { bareSuper.insertAfter(instanceBody); } } else { @@ -147,7 +147,7 @@ export default function ({ types: t }) { } } - for (let prop of props) { + for (const prop of props) { prop.remove(); } @@ -169,11 +169,11 @@ export default function ({ types: t }) { path.insertAfter(nodes); }, ArrowFunctionExpression(path) { - let classExp = path.get("body"); + const classExp = path.get("body"); if (!classExp.isClassExpression()) return; - let body = classExp.get("body"); - let members = body.get("body"); + const body = classExp.get("body"); + const members = body.get("body"); if (members.some((member) => member.isClassProperty())) { path.ensureBlock(); } diff --git a/packages/babel-plugin-transform-decorators/src/index.js b/packages/babel-plugin-transform-decorators/src/index.js index 1b3fbed6f81c..e1156b690390 100644 --- a/packages/babel-plugin-transform-decorators/src/index.js +++ b/packages/babel-plugin-transform-decorators/src/index.js @@ -1,7 +1,7 @@ import template from "babel-template"; import explodeClass from "babel-helper-explode-class"; -let buildClassDecorator = template(` +const buildClassDecorator = template(` CLASS_REF = DECORATOR(CLASS_REF) || CLASS_REF; `); @@ -11,7 +11,7 @@ export default function ({ types: t }) { } function transformClass(path, ref, state) { - let nodes = []; + const nodes = []; state; @@ -20,7 +20,7 @@ export default function ({ types: t }) { path.node.decorators = null; classDecorators = cleanDecorators(classDecorators); - for (let decorator of classDecorators) { + for (const decorator of classDecorators) { nodes.push(buildClassDecorator({ CLASS_REF: ref, DECORATOR: decorator @@ -28,21 +28,21 @@ export default function ({ types: t }) { } } - let map = Object.create(null); + const map = Object.create(null); - for (let method of path.get("body.body")) { - let decorators = method.node.decorators; + for (const method of path.get("body.body")) { + const decorators = method.node.decorators; if (!decorators) continue; - let alias = t.toKeyAlias(method.node); + const alias = t.toKeyAlias(method.node); map[alias] = map[alias] || []; map[alias].push(method.node); method.remove(); } - for (let alias in map) { - let items = map[alias]; + for (const alias in map) { + const items = map[alias]; items; } @@ -54,13 +54,13 @@ export default function ({ types: t }) { if (path.isClass()) { if (path.node.decorators) return true; - for (let method of (path.node.body.body: Array)) { + for (const method of (path.node.body.body: Array)) { if (method.decorators) { return true; } } } else if (path.isObjectExpression()) { - for (let prop of (path.node.properties: Array)) { + for (const prop of (path.node.properties: Array)) { if (prop.decorators) { return true; } @@ -97,7 +97,7 @@ The repo url is: https://github.com/loganfsmyth/babel-plugin-transform-decorator explodeClass(path); - let ref = path.scope.generateDeclaredUidIdentifier("ref"); + const ref = path.scope.generateDeclaredUidIdentifier("ref"); let nodes = []; nodes.push(t.assignmentExpression("=", ref, path.node)); @@ -114,7 +114,7 @@ The repo url is: https://github.com/loganfsmyth/babel-plugin-transform-decorator doError(path); explodeClass(path); - let ref = path.node.id; + const ref = path.node.id; let nodes = []; nodes = nodes.concat(transformClass(path, ref, this).map((expr) => t.expressionStatement(expr))); diff --git a/packages/babel-plugin-transform-do-expressions/src/index.js b/packages/babel-plugin-transform-do-expressions/src/index.js index 8bfe9c0dc59b..1354c4ecfab9 100644 --- a/packages/babel-plugin-transform-do-expressions/src/index.js +++ b/packages/babel-plugin-transform-do-expressions/src/index.js @@ -4,7 +4,7 @@ export default function () { visitor: { DoExpression(path) { - let body = path.node.body.body; + const body = path.node.body.body; if (body.length) { path.replaceWithMultiple(body); } else { diff --git a/packages/babel-plugin-transform-es2015-arrow-functions/src/index.js b/packages/babel-plugin-transform-es2015-arrow-functions/src/index.js index 1d4c91fee75a..70b610355673 100644 --- a/packages/babel-plugin-transform-es2015-arrow-functions/src/index.js +++ b/packages/babel-plugin-transform-es2015-arrow-functions/src/index.js @@ -3,13 +3,13 @@ export default function ({ types: t }) { visitor: { ArrowFunctionExpression(path, state) { if (state.opts.spec) { - let { node } = path; + const { node } = path; if (node.shadow) return; node.shadow = { this: false }; node.type = "FunctionExpression"; - let boundThis = t.thisExpression(); + const boundThis = t.thisExpression(); boundThis._forceShadow = path; // make sure that arrow function won't be instantiated diff --git a/packages/babel-plugin-transform-es2015-block-scoped-functions/src/index.js b/packages/babel-plugin-transform-es2015-block-scoped-functions/src/index.js index a1aac15dc38c..54d27f224c3d 100644 --- a/packages/babel-plugin-transform-es2015-block-scoped-functions/src/index.js +++ b/packages/babel-plugin-transform-es2015-block-scoped-functions/src/index.js @@ -1,12 +1,12 @@ export default function ({ types: t }) { function statementList(key, path) { - let paths: Array = path.get(key); + const paths: Array = path.get(key); - for (let path of paths) { - let func = path.node; + for (const path of paths) { + const func = path.node; if (!path.isFunctionDeclaration()) continue; - let declar = t.variableDeclaration("let", [ + const declar = t.variableDeclaration("let", [ t.variableDeclarator(func.id, t.toExpression(func)) ]); @@ -23,7 +23,7 @@ export default function ({ types: t }) { return { visitor: { BlockStatement(path) { - let { node, parent } = path; + const { node, parent } = path; if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) { return; } diff --git a/packages/babel-plugin-transform-es2015-block-scoping/src/index.js b/packages/babel-plugin-transform-es2015-block-scoping/src/index.js index 95b63d36b363..19a36f558c16 100644 --- a/packages/babel-plugin-transform-es2015-block-scoping/src/index.js +++ b/packages/babel-plugin-transform-es2015-block-scoping/src/index.js @@ -14,17 +14,17 @@ export default function () { return { visitor: { VariableDeclaration(path, file) { - let { node, parent, scope } = path; + const { node, parent, scope } = path; if (!isBlockScoped(node)) return; convertBlockScopedToVar(path, null, parent, scope, true); if (node._tdzThis) { - let nodes = [node]; + const nodes = [node]; for (let i = 0; i < node.declarations.length; i++) { - let decl = node.declarations[i]; + const decl = node.declarations[i]; if (decl.init) { - let assign = t.assignmentExpression("=", decl.id, decl.init); + const assign = t.assignmentExpression("=", decl.id, decl.init); assign._ignoreBlockScopingTDZ = true; nodes.push(t.expressionStatement(assign)); } @@ -44,22 +44,22 @@ export default function () { }, Loop(path, file) { - let { node, parent, scope } = path; + const { node, parent, scope } = path; t.ensureBlock(node); - let blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); - let replace = blockScoping.run(); + const blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); + const replace = blockScoping.run(); if (replace) path.replaceWith(replace); }, CatchClause(path, file) { - let { parent, scope } = path; - let blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); + const { parent, scope } = path; + const blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); blockScoping.run(); }, "BlockStatement|SwitchStatement|Program"(path, file) { if (!ignoreBlock(path)) { - let blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); + const blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); blockScoping.run(); } } @@ -71,7 +71,7 @@ function ignoreBlock(path) { return t.isLoop(path.parent) || t.isCatchClause(path.parent); } -let buildRetCheck = template(` +const buildRetCheck = template(` if (typeof RETURN === "object") return RETURN.v; `); @@ -89,7 +89,7 @@ function convertBlockScopedToVar(path, node, parent, scope, moveBindingsToParent // https://github.com/babel/babel/issues/255 if (!t.isFor(parent)) { for (let i = 0; i < node.declarations.length; i++) { - let declar = node.declarations[i]; + const declar = node.declarations[i]; declar.init = declar.init || scope.buildUndefinedNode(); } } @@ -101,8 +101,8 @@ function convertBlockScopedToVar(path, node, parent, scope, moveBindingsToParent if (moveBindingsToParent) { const parentScope = scope.getFunctionParent(); const ids = path.getBindingIdentifiers(); - for (let name in ids) { - let binding = scope.getOwnBinding(name); + for (const name in ids) { + const binding = scope.getOwnBinding(name); if (binding) binding.kind = "var"; scope.moveBindingTo(name, parentScope); } @@ -113,36 +113,36 @@ function isVar(node) { return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); } -let letReferenceBlockVisitor = traverse.visitors.merge([{ +const letReferenceBlockVisitor = traverse.visitors.merge([{ Function(path, state) { path.traverse(letReferenceFunctionVisitor, state); return path.skip(); } }, tdzVisitor]); -let letReferenceFunctionVisitor = traverse.visitors.merge([{ +const letReferenceFunctionVisitor = traverse.visitors.merge([{ ReferencedIdentifier(path, state) { - let ref = state.letReferences[path.node.name]; + const ref = state.letReferences[path.node.name]; // not a part of our scope if (!ref) return; // this scope has a variable with the same name so it couldn't belong // to our let scope - let localBinding = path.scope.getBindingIdentifier(path.node.name); + const localBinding = path.scope.getBindingIdentifier(path.node.name); if (localBinding && localBinding !== ref) return; state.closurify = true; } }, tdzVisitor]); -let hoistVarDeclarationsVisitor = { +const hoistVarDeclarationsVisitor = { enter(path, self) { - let { node, parent } = path; + const { node, parent } = path; if (path.isForStatement()) { if (isVar(node.init, node)) { - let nodes = self.pushDeclar(node.init); + const nodes = self.pushDeclar(node.init); if (nodes.length === 1) { node.init = nodes[0]; } else { @@ -162,17 +162,17 @@ let hoistVarDeclarationsVisitor = { } }; -let loopLabelVisitor = { +const loopLabelVisitor = { LabeledStatement({ node }, state) { state.innerLabels.push(node.label.name); } }; -let continuationVisitor = { +const continuationVisitor = { enter(path, state) { if (path.isAssignmentExpression() || path.isUpdateExpression()) { - let bindings = path.getBindingIdentifiers(); - for (let name in bindings) { + const bindings = path.getBindingIdentifiers(); + for (const name in bindings) { if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; state.reassignments[name] = true; } @@ -188,9 +188,9 @@ function loopNodeTo(node) { } } -let loopVisitor = { +const loopVisitor = { Loop(path, state) { - let oldIgnoreLabeless = state.ignoreLabeless; + const oldIgnoreLabeless = state.ignoreLabeless; state.ignoreLabeless = true; path.traverse(loopVisitor, state); state.ignoreLabeless = oldIgnoreLabeless; @@ -202,7 +202,7 @@ let loopVisitor = { }, SwitchCase(path, state) { - let oldInSwitchCase = state.inSwitchCase; + const oldInSwitchCase = state.inSwitchCase; state.inSwitchCase = true; path.traverse(loopVisitor, state); state.inSwitchCase = oldInSwitchCase; @@ -210,7 +210,7 @@ let loopVisitor = { }, "BreakStatement|ContinueStatement|ReturnStatement"(path, state) { - let { node, parent, scope } = path; + const { node, parent, scope } = path; if (node[this.LOOP_IGNORE]) return; let replace; @@ -284,11 +284,11 @@ class BlockScoping { */ run() { - let block = this.block; + const block = this.block; if (block._letDone) return; block._letDone = true; - let needsClosure = this.getLetReferences(); + const needsClosure = this.getLetReferences(); // this is a block within a `Function/Program` so we can safely leave it be if (t.isFunction(this.parent) || t.isProgram(this.block)) { @@ -313,12 +313,12 @@ class BlockScoping { } updateScopeInfo(wrappedInClosure) { - let scope = this.scope; - let parentScope = scope.getFunctionParent(); - let letRefs = this.letReferences; + const scope = this.scope; + const parentScope = scope.getFunctionParent(); + const letRefs = this.letReferences; - for (let key in letRefs) { - let ref = letRefs[key]; + for (const key in letRefs) { + const ref = letRefs[key]; const binding = scope.getBinding(ref.name); if (!binding) continue; if (binding.kind === "let" || binding.kind === "const") { @@ -334,18 +334,18 @@ class BlockScoping { } remap() { - let letRefs = this.letReferences; - let scope = this.scope; + const letRefs = this.letReferences; + const scope = this.scope; // alright, so since we aren't wrapping this block in a closure // we have to check if any of our let variables collide with // those in upper scopes and then if they do, generate a uid // for them and replace all references with it - for (let key in letRefs) { + for (const key in letRefs) { // just an Identifier node we collected in `getLetReferences` // this is the defining identifier of a declaration - let ref = letRefs[key]; + const ref = letRefs[key]; // todo: could skip this if the colliding binding is in another function if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { @@ -362,14 +362,14 @@ class BlockScoping { } wrapClosure() { - let block = this.block; + const block = this.block; - let outsideRefs = this.outsideLetReferences; + const outsideRefs = this.outsideLetReferences; // remap loop heads with colliding variables if (this.loop) { - for (let name in outsideRefs) { - let id = outsideRefs[name]; + for (const name in outsideRefs) { + const id = outsideRefs[name]; if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { delete outsideRefs[id.name]; @@ -391,13 +391,13 @@ class BlockScoping { this.hoistVarDeclarations(); // turn outsideLetReferences into an array - let params = values(outsideRefs); - let args = values(outsideRefs); + const params = values(outsideRefs); + const args = values(outsideRefs); const isSwitch = this.blockPath.isSwitchStatement(); // build the closure that we're going to wrap the block with, possible wrapping switch(){} - let fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); + const fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); fn.shadow = true; // continuation @@ -414,17 +414,17 @@ class BlockScoping { // build a call and a unique id that we can assign the return value to let call = t.callExpression(ref, args); - let ret = this.scope.generateUidIdentifier("ret"); + const ret = this.scope.generateUidIdentifier("ret"); // handle generators - let hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); + const hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); if (hasYield) { fn.generator = true; call = t.yieldExpression(call, true); } // handlers async functions - let hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); + const hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); if (hasAsync) { fn.async = true; call = t.awaitExpression(call); @@ -442,7 +442,7 @@ class BlockScoping { */ buildClosure(ret: { type: "Identifier" }, call: { type: "CallExpression" }) { - let has = this.has; + const has = this.has; if (has.hasReturn || has.hasBreakContinue) { this.buildHas(ret, call); } else { @@ -459,7 +459,7 @@ class BlockScoping { */ addContinuations(fn) { - let state = { + const state = { reassignments: {}, outsideReferences: this.outsideLetReferences }; @@ -467,10 +467,10 @@ class BlockScoping { this.scope.traverse(fn, continuationVisitor, state); for (let i = 0; i < fn.params.length; i++) { - let param = fn.params[i]; + const param = fn.params[i]; if (!state.reassignments[param.name]) continue; - let newParam = this.scope.generateUidIdentifier(param.name); + const newParam = this.scope.generateUidIdentifier(param.name); fn.params[i] = newParam; this.scope.rename(param.name, newParam.name, fn); @@ -481,12 +481,12 @@ class BlockScoping { } getLetReferences() { - let block = this.block; + const block = this.block; let declarators = []; if (this.loop) { - let init = this.loop.left || this.loop.init; + const init = this.loop.left || this.loop.init; if (isBlockScoped(init)) { declarators.push(init); extend(this.outsideLetReferences, t.getBindingIdentifiers(init)); @@ -509,18 +509,18 @@ class BlockScoping { // if (block.body) { for (let i = 0; i < block.body.length; i++) { - let declarPath = this.blockPath.get("body")[i]; + const declarPath = this.blockPath.get("body")[i]; addDeclarationsFromChild(declarPath); } } if (block.cases) { for (let i = 0; i < block.cases.length; i++) { - let consequents = block.cases[i].consequent; + const consequents = block.cases[i].consequent; for (let j = 0; j < consequents.length; j++) { - let declarPath = this.blockPath.get("cases")[i]; - let declar = consequents[j]; + const declarPath = this.blockPath.get("cases")[i]; + const declar = consequents[j]; addDeclarationsFromChild(declarPath, declar); } } @@ -528,12 +528,12 @@ class BlockScoping { // for (let i = 0; i < declarators.length; i++) { - let declar = declarators[i]; + const declar = declarators[i]; // Passing true as the third argument causes t.getBindingIdentifiers // to return only the *outer* binding identifiers of this // declaration, rather than (for example) mistakenly including the // parameters of a function declaration. Fixes #4880. - let keys = t.getBindingIdentifiers(declar, false, true); + const keys = t.getBindingIdentifiers(declar, false, true); extend(this.letReferences, keys); this.hasLetReferences = true; } @@ -541,7 +541,7 @@ class BlockScoping { // no let references so we can just quit if (!this.hasLetReferences) return; - let state = { + const state = { letReferences: this.letReferences, closurify: false, file: this.file @@ -562,7 +562,7 @@ class BlockScoping { */ checkLoop(): Object { - let state = { + const state = { hasBreakContinue: false, ignoreLabeless: false, inSwitchCase: false, @@ -594,21 +594,21 @@ class BlockScoping { */ pushDeclar(node: { type: "VariableDeclaration" }): Array { - let declars = []; - let names = t.getBindingIdentifiers(node); - for (let name in names) { + const declars = []; + const names = t.getBindingIdentifiers(node); + for (const name in names) { declars.push(t.variableDeclarator(names[name])); } this.body.push(t.variableDeclaration(node.kind, declars)); - let replace = []; + const replace = []; for (let i = 0; i < node.declarations.length; i++) { - let declar = node.declarations[i]; + const declar = node.declarations[i]; if (!declar.init) continue; - let expr = t.assignmentExpression("=", declar.id, declar.init); + const expr = t.assignmentExpression("=", declar.id, declar.init); replace.push(t.inherits(expr, declar)); } @@ -616,15 +616,15 @@ class BlockScoping { } buildHas(ret: { type: "Identifier" }, call: { type: "CallExpression" }) { - let body = this.body; + const body = this.body; body.push(t.variableDeclaration("var", [ t.variableDeclarator(ret, call) ])); let retCheck; - let has = this.has; - let cases = []; + const has = this.has; + const cases = []; if (has.hasReturn) { // typeof ret === "object" @@ -634,7 +634,7 @@ class BlockScoping { } if (has.hasBreakContinue) { - for (let key in has.map) { + for (const key in has.map) { cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); } @@ -643,7 +643,7 @@ class BlockScoping { } if (cases.length === 1) { - let single = cases[0]; + const single = cases[0]; body.push(t.ifStatement( t.binaryExpression("===", ret, single.test), single.consequent[0] @@ -652,7 +652,7 @@ class BlockScoping { if (this.loop) { // https://github.com/babel/babel/issues/998 for (let i = 0; i < cases.length; i++) { - let caseConsequent = cases[i].consequent[0]; + const caseConsequent = cases[i].consequent[0]; if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); } diff --git a/packages/babel-plugin-transform-es2015-block-scoping/src/tdz.js b/packages/babel-plugin-transform-es2015-block-scoping/src/tdz.js index 10d68c174dca..17a3c2d21057 100644 --- a/packages/babel-plugin-transform-es2015-block-scoping/src/tdz.js +++ b/packages/babel-plugin-transform-es2015-block-scoping/src/tdz.js @@ -1,7 +1,7 @@ import * as t from "babel-types"; function getTDZStatus(refPath, bindingPath) { - let executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); + const executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); if (executionStatus === "before") { return "inside"; @@ -20,29 +20,29 @@ function buildTDZAssert(node, file) { } function isReference(node, scope, state) { - let declared = state.letReferences[node.name]; + const declared = state.letReferences[node.name]; if (!declared) return false; // declared node is different in this scope return scope.getBindingIdentifier(node.name) === declared; } -export let visitor = { +export const visitor = { ReferencedIdentifier(path, state) { if (!this.file.opts.tdz) return; - let { node, parent, scope } = path; + const { node, parent, scope } = path; if (path.parentPath.isFor({ left: node })) return; if (!isReference(node, scope, state)) return; - let bindingPath = scope.getBinding(node.name).path; + const bindingPath = scope.getBinding(node.name).path; - let status = getTDZStatus(path, bindingPath); + const status = getTDZStatus(path, bindingPath); if (status === "inside") return; if (status === "maybe") { - let assert = buildTDZAssert(node, state.file); + const assert = buildTDZAssert(node, state.file); // add tdzThis to parent variable declarator so it's exploded bindingPath.parent._tdzThis = true; @@ -69,14 +69,14 @@ export let visitor = { exit(path, state) { if (!this.file.opts.tdz) return; - let { node } = path; + const { node } = path; if (node._ignoreBlockScopingTDZ) return; - let nodes = []; - let ids = path.getBindingIdentifiers(); + const nodes = []; + const ids = path.getBindingIdentifiers(); - for (let name in ids) { - let id = ids[name]; + for (const name in ids) { + const id = ids[name]; if (isReference(id, path.scope, state)) { nodes.push(buildTDZAssert(id, state.file)); diff --git a/packages/babel-plugin-transform-es2015-classes/src/index.js b/packages/babel-plugin-transform-es2015-classes/src/index.js index 9b4d371e5c91..2dc8e3337d0b 100644 --- a/packages/babel-plugin-transform-es2015-classes/src/index.js +++ b/packages/babel-plugin-transform-es2015-classes/src/index.js @@ -4,15 +4,15 @@ import nameFunction from "babel-helper-function-name"; export default function ({ types: t }) { // todo: investigate traversal requeueing - let VISITED = Symbol(); + const VISITED = Symbol(); return { visitor: { ExportDefaultDeclaration(path) { if (!path.get("declaration").isClassDeclaration()) return; - let { node } = path; - let ref = node.declaration.id || path.scope.generateUidIdentifier("class"); + const { node } = path; + const ref = node.declaration.id || path.scope.generateUidIdentifier("class"); node.declaration.id = ref; // Split the class declaration and the export into two separate statements. @@ -21,9 +21,9 @@ export default function ({ types: t }) { }, ClassDeclaration(path) { - let { node } = path; + const { node } = path; - let ref = node.id || path.scope.generateUidIdentifier("class"); + const ref = node.id || path.scope.generateUidIdentifier("class"); path.replaceWith(t.variableDeclaration("let", [ t.variableDeclarator(ref, t.toExpression(node)) @@ -31,10 +31,10 @@ export default function ({ types: t }) { }, ClassExpression(path, state) { - let { node } = path; + const { node } = path; if (node[VISITED]) return; - let inferred = nameFunction(path); + const inferred = nameFunction(path); if (inferred && inferred !== node) return path.replaceWith(inferred); node[VISITED] = true; diff --git a/packages/babel-plugin-transform-es2015-classes/src/lib/memoise-decorators.js b/packages/babel-plugin-transform-es2015-classes/src/lib/memoise-decorators.js index 294852818264..6583d081dc64 100644 --- a/packages/babel-plugin-transform-es2015-classes/src/lib/memoise-decorators.js +++ b/packages/babel-plugin-transform-es2015-classes/src/lib/memoise-decorators.js @@ -2,14 +2,14 @@ import type { Scope } from "babel-traverse"; import * as t from "babel-types"; export default function (decorators: Array, scope: Scope): Array { - for (let decorator of decorators) { - let expression = decorator.expression; + for (const decorator of decorators) { + const expression = decorator.expression; if (!t.isMemberExpression(expression)) continue; - let temp = scope.maybeGenerateMemoised(expression.object); + const temp = scope.maybeGenerateMemoised(expression.object); let ref; - let nodes = []; + const nodes = []; if (temp) { ref = temp; diff --git a/packages/babel-plugin-transform-es2015-classes/src/loose.js b/packages/babel-plugin-transform-es2015-classes/src/loose.js index 5c9122bacc0c..b94cd6be0516 100644 --- a/packages/babel-plugin-transform-es2015-classes/src/loose.js +++ b/packages/babel-plugin-transform-es2015-classes/src/loose.js @@ -14,11 +14,11 @@ export default class LooseClassTransformer extends VanillaTransformer { let classRef = this.classRef; if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); - let methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); + const methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); let func = t.functionExpression(null, node.params, node.body, node.generator, node.async); func.returnType = node.returnType; - let key = t.toComputedKey(node, node.key); + const key = t.toComputedKey(node, node.key); if (t.isStringLiteral(key)) { func = nameFunction({ node: func, @@ -27,7 +27,7 @@ export default class LooseClassTransformer extends VanillaTransformer { }); } - let expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); + const expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); t.inheritsComments(expr, node); this.body.push(expr); return true; diff --git a/packages/babel-plugin-transform-es2015-classes/src/vanilla.js b/packages/babel-plugin-transform-es2015-classes/src/vanilla.js index 34109568af80..b38a00fa0265 100644 --- a/packages/babel-plugin-transform-es2015-classes/src/vanilla.js +++ b/packages/babel-plugin-transform-es2015-classes/src/vanilla.js @@ -8,13 +8,13 @@ import * as defineMap from "babel-helper-define-map"; import template from "babel-template"; import * as t from "babel-types"; -let buildDerivedConstructor = template(` +const buildDerivedConstructor = template(` (function () { super(...arguments); }) `); -let noMethodVisitor = { +const noMethodVisitor = { "FunctionExpression|FunctionDeclaration"(path) { if (!path.is("shadow")) { path.skip(); @@ -26,7 +26,7 @@ let noMethodVisitor = { } }; -let verifyConstructorVisitor = visitors.merge([noMethodVisitor, { +const verifyConstructorVisitor = visitors.merge([noMethodVisitor, { Super(path) { if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { throw path.buildCodeFrameError("'super.*' is not allowed before super()"); @@ -54,7 +54,7 @@ let verifyConstructorVisitor = visitors.merge([noMethodVisitor, { } }]); -let findThisesVisitor = visitors.merge([noMethodVisitor, { +const findThisesVisitor = visitors.merge([noMethodVisitor, { ThisExpression(path) { this.superThises.push(path); } @@ -96,18 +96,18 @@ export default class ClassTransformer { run() { let superName = this.superName; - let file = this.file; + const file = this.file; let body = this.body; // - let constructorBody = this.constructorBody = t.blockStatement([]); + const constructorBody = this.constructorBody = t.blockStatement([]); this.constructor = this.buildConstructor(); // - let closureParams = []; - let closureArgs = []; + const closureParams = []; + const closureArgs = []; // if (this.isDerived) { @@ -138,13 +138,13 @@ export default class ClassTransformer { // body.push(t.returnStatement(this.classRef)); - let container = t.functionExpression(null, closureParams, t.blockStatement(body)); + const container = t.functionExpression(null, closureParams, t.blockStatement(body)); container.shadow = true; return t.callExpression(container, closureArgs); } buildConstructor() { - let func = t.functionDeclaration(this.classRef, [], this.constructorBody); + const func = t.functionDeclaration(this.classRef, [], this.constructorBody); t.inherits(func, this.node); return func; } @@ -159,7 +159,7 @@ export default class ClassTransformer { mutatorMap = this.instanceMutatorMap; } - let map = defineMap.push(mutatorMap, node, kind, this.file, scope); + const map = defineMap.push(mutatorMap, node, kind, this.file, scope); if (enumerable) { map.enumerable = t.booleanLiteral(true); @@ -175,8 +175,8 @@ export default class ClassTransformer { constructorMeMaybe() { let hasConstructor = false; - let paths = this.path.get("body.body"); - for (let path of (paths: Array)) { + const paths = this.path.get("body.body"); + for (const path of (paths: Array)) { hasConstructor = path.equals("kind", "constructor"); if (hasConstructor) break; } @@ -185,7 +185,7 @@ export default class ClassTransformer { let params, body; if (this.isDerived) { - let constructor = buildDerivedConstructor().expression; + const constructor = buildDerivedConstructor().expression; params = constructor.params; body = constructor.body; } else { @@ -207,7 +207,7 @@ export default class ClassTransformer { this.verifyConstructor(); if (this.userConstructor) { - let constructorBody = this.constructorBody; + const constructorBody = this.constructorBody; constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); t.inherits(this.constructor, this.userConstructor); t.inherits(constructorBody, this.userConstructor.body); @@ -217,10 +217,10 @@ export default class ClassTransformer { } pushBody() { - let classBodyPaths: Array = this.path.get("body.body"); + const classBodyPaths: Array = this.path.get("body.body"); - for (let path of classBodyPaths) { - let node = path.node; + for (const path of classBodyPaths) { + const node = path.node; if (path.isClassProperty()) { throw path.buildCodeFrameError("Missing class properties transform."); @@ -231,7 +231,7 @@ export default class ClassTransformer { } if (t.isClassMethod(node)) { - let isConstructor = node.kind === "constructor"; + const isConstructor = node.kind === "constructor"; if (isConstructor) { path.traverse(verifyConstructorVisitor, this); @@ -241,7 +241,7 @@ export default class ClassTransformer { } } - let replaceSupers = new ReplaceSupers({ + const replaceSupers = new ReplaceSupers({ forceSuperMemoisation: isConstructor, methodPath: path, methodNode: node, @@ -275,7 +275,7 @@ export default class ClassTransformer { pushDescriptors() { this.pushInherits(); - let body = this.body; + const body = this.body; let instanceProps; let staticProps; @@ -292,7 +292,7 @@ export default class ClassTransformer { if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); - let nullNode = t.nullLiteral(); + const nullNode = t.nullLiteral(); // (Constructor, instanceDescriptors, staticDescriptors, instanceInitializers, staticInitializers) let args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; @@ -363,7 +363,7 @@ export default class ClassTransformer { [t.thisExpression(), bareSuperNode] ); - let bareSuperAfter = this.bareSuperAfter.map((fn) => fn(thisRef)); + const bareSuperAfter = this.bareSuperAfter.map((fn) => fn(thisRef)); if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { // this super call is the last statement in the body so we can just straight up @@ -394,17 +394,17 @@ export default class ClassTransformer { verifyConstructor() { if (!this.isDerived) return; - let path = this.userConstructorPath; - let body = path.get("body"); + const path = this.userConstructorPath; + const body = path.get("body"); path.traverse(findThisesVisitor, this); let guaranteedSuperBeforeFinish = !!this.bareSupers.length; - let superRef = this.superName || t.identifier("Function"); - let thisRef = path.scope.generateUidIdentifier("this"); + const superRef = this.superName || t.identifier("Function"); + const thisRef = path.scope.generateUidIdentifier("this"); - for (let bareSuper of this.bareSupers) { + for (const bareSuper of this.bareSupers) { this.wrapSuperCall(bareSuper, superRef, thisRef, body); if (guaranteedSuperBeforeFinish) { @@ -422,25 +422,25 @@ export default class ClassTransformer { } } - for (let thisPath of this.superThises) { + for (const thisPath of this.superThises) { thisPath.replaceWith(thisRef); } - let wrapReturn = (returnArg) => t.callExpression( + const wrapReturn = (returnArg) => t.callExpression( this.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || []) ); // if we have a return as the last node in the body then we've already caught that // return - let bodyPaths = body.get("body"); + const bodyPaths = body.get("body"); if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); } - for (let returnPath of this.superReturns) { + for (const returnPath of this.superReturns) { if (returnPath.node.argument) { - let ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); + const ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); returnPath.get("argument").replaceWithMultiple([ t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref) @@ -456,7 +456,7 @@ export default class ClassTransformer { */ pushMethod(node: { type: "ClassMethod" }, path?: NodePath) { - let scope = path ? path.scope : this.scope; + const scope = path ? path.scope : this.scope; if (node.kind === "method") { if (this._processMethod(node, scope)) return; @@ -482,7 +482,7 @@ export default class ClassTransformer { path.scope.rename(this.classRef.name); } - let construct = this.constructor; + const construct = this.constructor; this.userConstructorPath = path; this.userConstructor = method; diff --git a/packages/babel-plugin-transform-es2015-computed-properties/src/index.js b/packages/babel-plugin-transform-es2015-computed-properties/src/index.js index 6bf843aaab7e..ac0ef38fc8b0 100644 --- a/packages/babel-plugin-transform-es2015-computed-properties/src/index.js +++ b/packages/babel-plugin-transform-es2015-computed-properties/src/index.js @@ -1,5 +1,5 @@ export default function ({ types: t, template }) { - let buildMutatorMapAssign = template(` + const buildMutatorMapAssign = template(` MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {}; MUTATOR_MAP_REF[KEY].KIND = VALUE; `); @@ -29,7 +29,7 @@ export default function ({ types: t, template }) { function pushMutatorDefine({ objId, body, getMutatorId, scope }, prop) { let key = !prop.computed && t.isIdentifier(prop.key) ? t.stringLiteral(prop.key.name) : prop.key; - let maybeMemoise = scope.maybeGenerateMemoised(key); + const maybeMemoise = scope.maybeGenerateMemoised(key); if (maybeMemoise) { body.push(t.expressionStatement(t.assignmentExpression("=", maybeMemoise, key))); key = maybeMemoise; @@ -44,7 +44,7 @@ export default function ({ types: t, template }) { } function loose(info) { - for (let prop of info.computedProps) { + for (const prop of info.computedProps) { if (prop.kind === "get" || prop.kind === "set") { pushMutatorDefine(info, prop); } else { @@ -54,10 +54,10 @@ export default function ({ types: t, template }) { } function spec(info) { - let { objId, body, computedProps, state } = info; + const { objId, body, computedProps, state } = info; - for (let prop of computedProps) { - let key = t.toComputedKey(prop); + for (const prop of computedProps) { + const key = t.toComputedKey(prop); if (prop.kind === "get" || prop.kind === "set") { pushMutatorDefine(info, prop); @@ -87,9 +87,9 @@ export default function ({ types: t, template }) { visitor: { ObjectExpression: { exit(path, state) { - let { node, parent, scope } = path; + const { node, parent, scope } = path; let hasComputed = false; - for (let prop of (node.properties: Array)) { + for (const prop of (node.properties: Array)) { hasComputed = prop.computed === true; if (hasComputed) break; } @@ -98,11 +98,11 @@ export default function ({ types: t, template }) { // put all getters/setters into the first object expression as well as all initialisers up // to the first computed property - let initProps = []; - let computedProps = []; + const initProps = []; + const computedProps = []; let foundComputed = false; - for (let prop of node.properties) { + for (const prop of node.properties) { if (prop.computed) { foundComputed = true; } @@ -114,9 +114,9 @@ export default function ({ types: t, template }) { } } - let objId = scope.generateUidIdentifierBasedOnNode(parent); - let initPropExpression = t.objectExpression(initProps); - let body = []; + const objId = scope.generateUidIdentifierBasedOnNode(parent); + const initPropExpression = t.objectExpression(initProps); + const body = []; body.push(t.variableDeclaration("var", [ t.variableDeclarator(objId, initPropExpression) @@ -127,7 +127,7 @@ export default function ({ types: t, template }) { let mutatorRef; - let getMutatorId = function () { + const getMutatorId = function () { if (!mutatorRef) { mutatorRef = scope.generateUidIdentifier("mutatorMap"); @@ -139,7 +139,7 @@ export default function ({ types: t, template }) { return mutatorRef; }; - let single = callback({ + const single = callback({ scope, objId, body, diff --git a/packages/babel-plugin-transform-es2015-destructuring/src/index.js b/packages/babel-plugin-transform-es2015-destructuring/src/index.js index 3fe8c9fd3bf7..6184cf2547e6 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/src/index.js +++ b/packages/babel-plugin-transform-es2015-destructuring/src/index.js @@ -7,7 +7,7 @@ export default function ({ types: t }) { */ function variableDeclarationHasPattern(node) { - for (let declar of (node.declarations: Array)) { + for (const declar of (node.declarations: Array)) { if (t.isPattern(declar.id)) { return true; } @@ -20,7 +20,7 @@ export default function ({ types: t }) { */ function hasRest(pattern) { - for (let elem of (pattern.elements: Array)) { + for (const elem of (pattern.elements: Array)) { if (t.isRestElement(elem)) { return true; } @@ -28,7 +28,7 @@ export default function ({ types: t }) { return false; } - let arrayUnpackVisitor = { + const arrayUnpackVisitor = { ReferencedIdentifier(path, state) { if (state.bindings[path.node.name]) { state.deopt = true; @@ -68,7 +68,7 @@ export default function ({ types: t }) { } buildVariableDeclaration(id, init) { - let declar = t.variableDeclaration("var", [ + const declar = t.variableDeclaration("var", [ t.variableDeclarator(id, init) ]); declar._blockHoist = this.blockHoist; @@ -99,9 +99,9 @@ export default function ({ types: t }) { // we need to assign the current value of the assignment to avoid evaluating // it more than once - let tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); + const tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); - let declar = t.variableDeclaration("var", [ + const declar = t.variableDeclaration("var", [ t.variableDeclarator(tempValueRef, valueRef) ]); declar._blockHoist = this.blockHoist; @@ -109,15 +109,15 @@ export default function ({ types: t }) { // - let tempConditional = t.conditionalExpression( + const tempConditional = t.conditionalExpression( t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef ); - let left = pattern.left; + const left = pattern.left; if (t.isPattern(left)) { - let tempValueDefault = t.expressionStatement( + const tempValueDefault = t.expressionStatement( t.assignmentExpression("=", tempValueRef, tempConditional) ); tempValueDefault._blockHoist = this.blockHoist; @@ -135,7 +135,7 @@ export default function ({ types: t }) { let keys = []; for (let i = 0; i < pattern.properties.length; i++) { - let prop = pattern.properties[i]; + const prop = pattern.properties[i]; // we've exceeded the index of the spread property to all properties to the // right need to be ignored @@ -153,15 +153,15 @@ export default function ({ types: t }) { // - let value = t.callExpression(this.file.addHelper("objectWithoutProperties"), [objRef, keys]); + const value = t.callExpression(this.file.addHelper("objectWithoutProperties"), [objRef, keys]); this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); } pushObjectProperty(prop, propRef) { if (t.isLiteral(prop.key)) prop.computed = true; - let pattern = prop.value; - let objRef = t.memberExpression(propRef, prop.key, prop.computed); + const pattern = prop.value; + const objRef = t.memberExpression(propRef, prop.key, prop.computed); if (t.isPattern(pattern)) { this.push(pattern, objRef); @@ -184,7 +184,7 @@ export default function ({ types: t }) { // only evaluated once if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) { - let temp = this.scope.generateUidIdentifierBasedOnNode(objRef); + const temp = this.scope.generateUidIdentifierBasedOnNode(objRef); this.nodes.push(this.buildVariableDeclaration(temp, objRef)); objRef = temp; } @@ -192,7 +192,7 @@ export default function ({ types: t }) { // for (let i = 0; i < pattern.properties.length; i++) { - let prop = pattern.properties[i]; + const prop = pattern.properties[i]; if (t.isRestProperty(prop)) { this.pushObjectRest(pattern, objRef, prop, i); } else { @@ -210,7 +210,7 @@ export default function ({ types: t }) { if (pattern.elements.length > arr.elements.length) return; if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; - for (let elem of (pattern.elements: Array)) { + for (const elem of (pattern.elements: Array)) { // deopt on holes if (!elem) return false; @@ -218,7 +218,7 @@ export default function ({ types: t }) { if (t.isMemberExpression(elem)) return false; } - for (let elem of (arr.elements: Array)) { + for (const elem of (arr.elements: Array)) { // deopt on spread elements if (t.isSpreadElement(elem)) return false; @@ -230,15 +230,15 @@ export default function ({ types: t }) { } // deopt on reference to left side identifiers - let bindings = t.getBindingIdentifiers(pattern); - let state = { deopt: false, bindings }; + const bindings = t.getBindingIdentifiers(pattern); + const state = { deopt: false, bindings }; this.scope.traverse(arr, arrayUnpackVisitor, state); return !state.deopt; } pushUnpackedArrayPattern(pattern, arr) { for (let i = 0; i < pattern.elements.length; i++) { - let elem = pattern.elements[i]; + const elem = pattern.elements[i]; if (t.isRestElement(elem)) { this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); } else { @@ -264,13 +264,13 @@ export default function ({ types: t }) { // if we have a rest then we need all the elements so don't tell // `scope.toArray` to only get a certain amount - let count = !hasRest(pattern) && pattern.elements.length; + const count = !hasRest(pattern) && pattern.elements.length; // so we need to ensure that the `arrayRef` is an array, `scope.toArray` will // return a locally bound identifier if it's been inferred to be an array, // otherwise it'll be a call to a helper that will ensure it's one - let toArray = this.toArray(arrayRef, count); + const toArray = this.toArray(arrayRef, count); if (t.isIdentifier(toArray)) { // we've been given an identifier so it must have been inferred to be an @@ -315,7 +315,7 @@ export default function ({ types: t }) { // need to save it to a variable if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) { - let memo = this.scope.maybeGenerateMemoised(ref, true); + const memo = this.scope.maybeGenerateMemoised(ref, true); if (memo) { this.nodes.push(this.buildVariableDeclaration(memo, ref)); ref = memo; @@ -334,14 +334,14 @@ export default function ({ types: t }) { return { visitor: { ExportNamedDeclaration(path) { - let declaration = path.get("declaration"); + const declaration = path.get("declaration"); if (!declaration.isVariableDeclaration()) return; if (!variableDeclarationHasPattern(declaration.node)) return; - let specifiers = []; + const specifiers = []; - for (let name in path.getOuterBindingIdentifiers(path)) { - let id = t.identifier(name); + for (const name in path.getOuterBindingIdentifiers(path)) { + const id = t.identifier(name); specifiers.push(t.exportSpecifier(id, id)); } @@ -353,13 +353,13 @@ export default function ({ types: t }) { }, ForXStatement(path, file) { - let { node, scope } = path; - let left = node.left; + const { node, scope } = path; + const left = node.left; if (t.isPattern(left)) { // for ({ length: k } in { abc: 3 }); - let temp = scope.generateUidIdentifier("ref"); + const temp = scope.generateUidIdentifier("ref"); node.left = t.variableDeclaration("var", [ t.variableDeclarator(temp) @@ -376,17 +376,17 @@ export default function ({ types: t }) { if (!t.isVariableDeclaration(left)) return; - let pattern = left.declarations[0].id; + const pattern = left.declarations[0].id; if (!t.isPattern(pattern)) return; - let key = scope.generateUidIdentifier("ref"); + const key = scope.generateUidIdentifier("ref"); node.left = t.variableDeclaration(left.kind, [ t.variableDeclarator(key, null) ]); - let nodes = []; + const nodes = []; - let destructuring = new DestructuringTransformer({ + const destructuring = new DestructuringTransformer({ kind: left.kind, file: file, scope: scope, @@ -397,20 +397,20 @@ export default function ({ types: t }) { path.ensureBlock(); - let block = node.body; + const block = node.body; block.body = nodes.concat(block.body); }, CatchClause({ node, scope }, file) { - let pattern = node.param; + const pattern = node.param; if (!t.isPattern(pattern)) return; - let ref = scope.generateUidIdentifier("ref"); + const ref = scope.generateUidIdentifier("ref"); node.param = ref; - let nodes = []; + const nodes = []; - let destructuring = new DestructuringTransformer({ + const destructuring = new DestructuringTransformer({ kind: "let", file: file, scope: scope, @@ -422,12 +422,12 @@ export default function ({ types: t }) { }, AssignmentExpression(path, file) { - let { node, scope } = path; + const { node, scope } = path; if (!t.isPattern(node.left)) return; - let nodes = []; + const nodes = []; - let destructuring = new DestructuringTransformer({ + const destructuring = new DestructuringTransformer({ operator: node.operator, file: file, scope: scope, @@ -457,21 +457,21 @@ export default function ({ types: t }) { }, VariableDeclaration(path, file) { - let { node, scope, parent } = path; + const { node, scope, parent } = path; if (t.isForXStatement(parent)) return; if (!parent || !path.container) return; // i don't know why this is necessary - TODO if (!variableDeclarationHasPattern(node)) return; - let nodes = []; + const nodes = []; let declar; for (let i = 0; i < node.declarations.length; i++) { declar = node.declarations[i]; - let patternId = declar.init; - let pattern = declar.id; + const patternId = declar.init; + const pattern = declar.id; - let destructuring = new DestructuringTransformer({ + const destructuring = new DestructuringTransformer({ blockHoist: node._blockHoist, nodes: nodes, scope: scope, diff --git a/packages/babel-plugin-transform-es2015-duplicate-keys/src/index.js b/packages/babel-plugin-transform-es2015-duplicate-keys/src/index.js index 551e27a4ecd7..f2d7a6990f25 100644 --- a/packages/babel-plugin-transform-es2015-duplicate-keys/src/index.js +++ b/packages/babel-plugin-transform-es2015-duplicate-keys/src/index.js @@ -26,27 +26,27 @@ export default function() { const alreadySeenGetters = Object.create(null); const alreadySeenSetters = Object.create(null); - for (let prop of plainProps) { + for (const prop of plainProps) { const name = getName(prop.key); let isDuplicate = false; switch (prop.kind) { - case "get": - if (alreadySeenData[name] || alreadySeenGetters[name]) { - isDuplicate = true; - } - alreadySeenGetters[name] = true; - break; - case "set": - if (alreadySeenData[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenSetters[name] = true; - break; - default: - if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenData[name] = true; + case "get": + if (alreadySeenData[name] || alreadySeenGetters[name]) { + isDuplicate = true; + } + alreadySeenGetters[name] = true; + break; + case "set": + if (alreadySeenData[name] || alreadySeenSetters[name]) { + isDuplicate = true; + } + alreadySeenSetters[name] = true; + break; + default: + if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) { + isDuplicate = true; + } + alreadySeenData[name] = true; } if (isDuplicate) { diff --git a/packages/babel-plugin-transform-es2015-for-of/src/index.js b/packages/babel-plugin-transform-es2015-for-of/src/index.js index ca5ab6c09084..760e0e69b00c 100644 --- a/packages/babel-plugin-transform-es2015-for-of/src/index.js +++ b/packages/babel-plugin-transform-es2015-for-of/src/index.js @@ -1,11 +1,11 @@ /* eslint max-len: 0 */ export default function ({ messages, template, types: t }) { - let buildForOfArray = template(` + const buildForOfArray = template(` for (var KEY = 0; KEY < ARR.length; KEY++) BODY; `); - let buildForOfLoose = template(` + const buildForOfLoose = template(` for (var LOOP_OBJECT = OBJECT, IS_ARRAY = Array.isArray(LOOP_OBJECT), INDEX = 0, @@ -22,7 +22,7 @@ export default function ({ messages, template, types: t }) { } `); - let buildForOf = template(` + const buildForOf = template(` var ITERATOR_COMPLETION = true; var ITERATOR_HAD_ERROR_KEY = false; var ITERATOR_ERROR_KEY = undefined; @@ -46,19 +46,19 @@ export default function ({ messages, template, types: t }) { `); function _ForOfStatementArray(path) { - let { node, scope } = path; - let nodes = []; + const { node, scope } = path; + const nodes = []; let right = node.right; if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { - let uid = scope.generateUidIdentifier("arr"); + const uid = scope.generateUidIdentifier("arr"); nodes.push(t.variableDeclaration("var", [ t.variableDeclarator(uid, right) ])); right = uid; } - let iterationKey = scope.generateUidIdentifier("i"); + const iterationKey = scope.generateUidIdentifier("i"); let loop = buildForOfArray({ BODY: node.body, @@ -69,9 +69,9 @@ export default function ({ messages, template, types: t }) { t.inherits(loop, node); t.ensureBlock(loop); - let iterationValue = t.memberExpression(right, iterationKey, true); + const iterationValue = t.memberExpression(right, iterationKey, true); - let left = node.left; + const left = node.left; if (t.isVariableDeclaration(left)) { left.declarations[0].init = iterationValue; loop.body.body.unshift(left); @@ -103,11 +103,11 @@ export default function ({ messages, template, types: t }) { let callback = spec; if (state.opts.loose) callback = loose; - let { node } = path; - let build = callback(path, state); - let declar = build.declar; - let loop = build.loop; - let block = loop.body; + const { node } = path; + const build = callback(path, state); + const declar = build.declar; + const loop = build.loop; + const block = loop.body; // ensure that it's a block so we can take all its statements path.ensureBlock(); @@ -134,9 +134,9 @@ export default function ({ messages, template, types: t }) { }; function loose(path, file) { - let { node, scope } = path; + const { node, scope } = path; - let left = node.left; + const left = node.left; let declar, id; if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { @@ -152,10 +152,10 @@ export default function ({ messages, template, types: t }) { throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); } - let iteratorKey = scope.generateUidIdentifier("iterator"); - let isArrayKey = scope.generateUidIdentifier("isArray"); + const iteratorKey = scope.generateUidIdentifier("iterator"); + const isArrayKey = scope.generateUidIdentifier("isArray"); - let loop = buildForOfLoose({ + const loop = buildForOfLoose({ LOOP_OBJECT: iteratorKey, IS_ARRAY: isArrayKey, OBJECT: node.right, @@ -179,12 +179,12 @@ export default function ({ messages, template, types: t }) { } function spec(path, file) { - let { node, scope, parent } = path; - let left = node.left; + const { node, scope, parent } = path; + const left = node.left; let declar; - let stepKey = scope.generateUidIdentifier("step"); - let stepValue = t.memberExpression(stepKey, t.identifier("value")); + const stepKey = scope.generateUidIdentifier("step"); + const stepValue = t.memberExpression(stepKey, t.identifier("value")); if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { // for (i of test), for ({ i } of test) @@ -200,9 +200,9 @@ export default function ({ messages, template, types: t }) { // - let iteratorKey = scope.generateUidIdentifier("iterator"); + const iteratorKey = scope.generateUidIdentifier("iterator"); - let template = buildForOf({ + const template = buildForOf({ ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), @@ -212,10 +212,10 @@ export default function ({ messages, template, types: t }) { BODY: null }); - let isLabeledParent = t.isLabeledStatement(parent); + const isLabeledParent = t.isLabeledStatement(parent); - let tryBody = template[3].block.body; - let loop = tryBody[0]; + const tryBody = template[3].block.body; + const loop = tryBody[0]; if (isLabeledParent) { tryBody[0] = t.labeledStatement(parent.label, loop); diff --git a/packages/babel-plugin-transform-es2015-function-name/src/index.js b/packages/babel-plugin-transform-es2015-function-name/src/index.js index ab403e6ec5f1..6fdeedd06935 100644 --- a/packages/babel-plugin-transform-es2015-function-name/src/index.js +++ b/packages/babel-plugin-transform-es2015-function-name/src/index.js @@ -6,16 +6,16 @@ export default function () { "ArrowFunctionExpression|FunctionExpression": { exit(path) { if (path.key !== "value" && !path.parentPath.isObjectProperty()) { - let replacement = nameFunction(path); + const replacement = nameFunction(path); if (replacement) path.replaceWith(replacement); } } }, ObjectProperty(path) { - let value = path.get("value"); + const value = path.get("value"); if (value.isFunction()) { - let newNode = nameFunction(value); + const newNode = nameFunction(value); if (newNode) value.replaceWith(newNode); } } diff --git a/packages/babel-plugin-transform-es2015-instanceof/src/index.js b/packages/babel-plugin-transform-es2015-instanceof/src/index.js index d12f4c6fc98c..ff744f9cff64 100644 --- a/packages/babel-plugin-transform-es2015-instanceof/src/index.js +++ b/packages/babel-plugin-transform-es2015-instanceof/src/index.js @@ -2,7 +2,7 @@ export default function ({ types: t }) { return { visitor: { BinaryExpression(path) { - let { node } = path; + const { node } = path; if (node.operator === "instanceof") { path.replaceWith(t.callExpression(this.addHelper("instanceof"), [node.left, node.right])); } diff --git a/packages/babel-plugin-transform-es2015-modules-amd/src/index.js b/packages/babel-plugin-transform-es2015-modules-amd/src/index.js index 3c5f9243bc8f..bb9eb42c9614 100644 --- a/packages/babel-plugin-transform-es2015-modules-amd/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-amd/src/index.js @@ -1,10 +1,10 @@ import template from "babel-template"; -let buildDefine = template(` +const buildDefine = template(` define(MODULE_NAME, [SOURCES], FACTORY); `); -let buildFactory = template(` +const buildFactory = template(` (function (PARAMS) { BODY; }) @@ -16,16 +16,16 @@ export default function ({ types: t }) { if (!path.get("callee").isIdentifier({ name: "require" })) return false; if (path.scope.getBinding("require")) return false; - let args = path.get("arguments"); + const args = path.get("arguments"); if (args.length !== 1) return false; - let arg = args[0]; + const arg = args[0]; if (!arg.isStringLiteral()) return false; return true; } - let amdVisitor = { + const amdVisitor = { ReferencedIdentifier({ node, scope }) { if (node.name === "exports" && !scope.getBinding("exports")) { this.hasExports = true; @@ -43,13 +43,13 @@ export default function ({ types: t }) { }, VariableDeclarator(path) { - let id = path.get("id"); + const id = path.get("id"); if (!id.isIdentifier()) return; - let init = path.get("init"); + const init = path.get("init"); if (!isValidRequireCall(init)) return; - let source = init.node.arguments[0]; + const source = init.node.arguments[0]; this.sourceNames[source.value] = true; this.sources.push([id.node, source]); @@ -80,7 +80,7 @@ export default function ({ types: t }) { path.traverse(amdVisitor, this); - let params = this.sources.map((source) => source[0]); + const params = this.sources.map((source) => source[0]); let sources = this.sources.map((source) => source[1]); sources = sources.concat(this.bareSources.filter((str) => { @@ -100,8 +100,8 @@ export default function ({ types: t }) { params.unshift(t.identifier("module")); } - let { node } = path; - let factory = buildFactory({ + const { node } = path; + const factory = buildFactory({ PARAMS: params, BODY: node.body }); diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js b/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js index 8d3351bfa92e..a7285da44645 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js @@ -4,17 +4,17 @@ import { basename, extname } from "path"; import template from "babel-template"; import * as t from "babel-types"; -let buildRequire = template(` +const buildRequire = template(` require($0); `); -let buildExportsModuleDeclaration = template(` +const buildExportsModuleDeclaration = template(` Object.defineProperty(exports, "__esModule", { value: true }); `); -let buildExportsFrom = template(` +const buildExportsFrom = template(` Object.defineProperty(exports, $0, { enumerable: true, get: function () { @@ -23,15 +23,15 @@ let buildExportsFrom = template(` }); `); -let buildLooseExportsModuleDeclaration = template(` +const buildLooseExportsModuleDeclaration = template(` exports.__esModule = true; `); -let buildExportsAssignment = template(` +const buildExportsAssignment = template(` exports.$0 = $1; `); -let buildExportAll = template(` +const buildExportAll = template(` Object.keys(OBJECT).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { @@ -46,12 +46,12 @@ let buildExportAll = template(` const THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod"]; export default function () { - let REASSIGN_REMAP_SKIP = Symbol(); + const REASSIGN_REMAP_SKIP = Symbol(); - let reassignmentVisitor = { + const reassignmentVisitor = { ReferencedIdentifier(path) { - let name = path.node.name; - let remap = this.remaps[name]; + const name = path.node.name; + const remap = this.remaps[name]; if (!remap) return; // redeclared in this scope @@ -72,11 +72,11 @@ export default function () { let node = path.node; if (node[REASSIGN_REMAP_SKIP]) return; - let left = path.get("left"); + const left = path.get("left"); if (!left.isIdentifier()) return; - let name = left.node.name; - let exports = this.exports[name]; + const name = left.node.name; + const exports = this.exports[name]; if (!exports) return; // redeclared in this scope @@ -84,7 +84,7 @@ export default function () { node[REASSIGN_REMAP_SKIP] = true; - for (let reid of exports) { + for (const reid of exports) { node = buildExportsAssignment(reid, node).expression; } @@ -93,17 +93,17 @@ export default function () { }, UpdateExpression(path) { - let arg = path.get("argument"); + const arg = path.get("argument"); if (!arg.isIdentifier()) return; - let name = arg.node.name; - let exports = this.exports[name]; + const name = arg.node.name; + const exports = this.exports[name]; if (!exports) return; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - let node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); + const node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); if ((path.parentPath.isExpressionStatement() && !path.isCompletionRecord()) || path.node.prefix) { path.replaceWith(node); @@ -111,7 +111,7 @@ export default function () { return; } - let nodes = []; + const nodes = []; nodes.push(node); let operator; @@ -149,9 +149,9 @@ export default function () { exit(path) { this.ranCommonJS = true; - let strict = !!this.opts.strict; + const strict = !!this.opts.strict; - let { scope } = path; + const { scope } = path; // rename these commonjs variables if they're declared in the file scope.rename("module"); @@ -161,24 +161,24 @@ export default function () { let hasExports = false; let hasImports = false; - let body: Array = path.get("body"); - let imports = Object.create(null); - let exports = Object.create(null); + const body: Array = path.get("body"); + const imports = Object.create(null); + const exports = Object.create(null); - let nonHoistedExportNames = Object.create(null); + const nonHoistedExportNames = Object.create(null); - let topNodes = []; - let remaps = Object.create(null); + const topNodes = []; + const remaps = Object.create(null); - let requires = Object.create(null); + const requires = Object.create(null); function addRequire(source, blockHoist) { - let cached = requires[source]; + const cached = requires[source]; if (cached) return cached; - let ref = path.scope.generateUidIdentifier(basename(source, extname(source))); + const ref = path.scope.generateUidIdentifier(basename(source, extname(source))); - let varDecl = t.variableDeclaration("var", [ + const varDecl = t.variableDeclaration("var", [ t.variableDeclarator(ref, buildRequire( t.stringLiteral(source) ).expression) @@ -200,17 +200,17 @@ export default function () { } function addTo(obj, key, arr) { - let existing = obj[key] || []; + const existing = obj[key] || []; obj[key] = existing.concat(arr); } - for (let path of body) { + for (const path of body) { if (path.isExportDeclaration()) { hasExports = true; - let specifiers = [].concat(path.get("declaration"), path.get("specifiers")); - for (let specifier of specifiers) { - let ids = specifier.getBindingIdentifiers(); + const specifiers = [].concat(path.get("declaration"), path.get("specifiers")); + for (const specifier of specifiers) { + const ids = specifier.getBindingIdentifiers(); if (ids.__esModule) { throw specifier.buildCodeFrameError("Illegal export \"__esModule\""); } @@ -220,8 +220,8 @@ export default function () { if (path.isImportDeclaration()) { hasImports = true; - let key = path.node.source.value; - let importsEntry = imports[key] || { + const key = path.node.source.value; + const importsEntry = imports[key] || { specifiers: [], maxBlockHoist: 0, loc: path.node.loc, @@ -240,10 +240,10 @@ export default function () { path.remove(); } else if (path.isExportDefaultDeclaration()) { - let declaration = path.get("declaration"); + const declaration = path.get("declaration"); if (declaration.isFunctionDeclaration()) { - let id = declaration.node.id; - let defNode = t.identifier("default"); + const id = declaration.node.id; + const defNode = t.identifier("default"); if (id) { addTo(exports, id.name, defNode); topNodes.push(buildExportsAssignment(defNode, id)); @@ -253,8 +253,8 @@ export default function () { path.remove(); } } else if (declaration.isClassDeclaration()) { - let id = declaration.node.id; - let defNode = t.identifier("default"); + const id = declaration.node.id; + const defNode = t.identifier("default"); if (id) { addTo(exports, id.name, defNode); path.replaceWithMultiple([ @@ -278,15 +278,15 @@ export default function () { path.parentPath.requeue(path.get("expression.left")); } } else if (path.isExportNamedDeclaration()) { - let declaration = path.get("declaration"); + const declaration = path.get("declaration"); if (declaration.node) { if (declaration.isFunctionDeclaration()) { - let id = declaration.node.id; + const id = declaration.node.id; addTo(exports, id.name, id); topNodes.push(buildExportsAssignment(id, id)); path.replaceWith(declaration.node); } else if (declaration.isClassDeclaration()) { - let id = declaration.node.id; + const id = declaration.node.id; addTo(exports, id.name, id); path.replaceWithMultiple([ declaration.node, @@ -294,11 +294,11 @@ export default function () { ]); nonHoistedExportNames[id.name] = true; } else if (declaration.isVariableDeclaration()) { - let declarators = declaration.get("declarations"); - for (let decl of declarators) { - let id = decl.get("id"); + const declarators = declaration.get("declarations"); + for (const decl of declarators) { + const id = decl.get("id"); - let init = decl.get("init"); + const init = decl.get("init"); if (!init.node) init.replaceWith(t.identifier("undefined")); if (id.isIdentifier()) { @@ -314,13 +314,13 @@ export default function () { continue; } - let specifiers = path.get("specifiers"); - let nodes = []; - let source = path.node.source; + const specifiers = path.get("specifiers"); + const nodes = []; + const source = path.node.source; if (source) { - let ref = addRequire(source.value, path.node._blockHoist); + const ref = addRequire(source.value, path.node._blockHoist); - for (let specifier of specifiers) { + for (const specifier of specifiers) { if (specifier.isExportNamespaceSpecifier()) { // todo } else if (specifier.isExportDefaultSpecifier()) { @@ -335,7 +335,7 @@ export default function () { } } } else { - for (let specifier of specifiers) { + for (const specifier of specifiers) { if (specifier.isExportSpecifier()) { addTo(exports, specifier.node.local.name, specifier.node.exported); nonHoistedExportNames[specifier.node.exported.name] = true; @@ -345,7 +345,7 @@ export default function () { } path.replaceWithMultiple(nodes); } else if (path.isExportAllDeclaration()) { - let exportNode = buildExportAll({ + const exportNode = buildExportAll({ OBJECT: addRequire(path.node.source.value, path.node._blockHoist) }); exportNode.loc = path.node.loc; @@ -354,15 +354,15 @@ export default function () { } } - for (let source in imports) { - let {specifiers, maxBlockHoist} = imports[source]; + for (const source in imports) { + const {specifiers, maxBlockHoist} = imports[source]; if (specifiers.length) { - let uid = addRequire(source, maxBlockHoist); + const uid = addRequire(source, maxBlockHoist); let wildcard; for (let i = 0; i < specifiers.length; i++) { - let specifier = specifiers[i]; + const specifier = specifiers[i]; if (t.isImportNamespaceSpecifier(specifier)) { if (strict) { remaps[specifier.local.name] = uid; @@ -389,7 +389,7 @@ export default function () { } } - for (let specifier of specifiers) { + for (const specifier of specifiers) { if (t.isImportSpecifier(specifier)) { let target = uid; if (specifier.imported.name === "default") { @@ -419,7 +419,7 @@ export default function () { } } else { // bare import - let requireNode = buildRequire(t.stringLiteral(source)); + const requireNode = buildRequire(t.stringLiteral(source)); requireNode.loc = imports[source].loc; topNodes.push(requireNode); } @@ -428,7 +428,7 @@ export default function () { if (hasImports && Object.keys(nonHoistedExportNames).length) { let hoistedExportsNode = t.identifier("undefined"); - for (let name in nonHoistedExportNames) { + for (const name in nonHoistedExportNames) { hoistedExportsNode = buildExportsAssignment(t.identifier(name), hoistedExportsNode).expression; } diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js b/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js index beee1e9cd3ee..2ab422c89b68 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js @@ -1,14 +1,14 @@ -let assert = require("assert"); -let babel = require("babel-core"); -let vm = require("vm"); +const assert = require("assert"); +const babel = require("babel-core"); +const vm = require("vm"); test("Re-export doesn't overwrite __esModule flag", function () { let code = "export * from \"./dep\";"; - let depStub = { + const depStub = { __esModule: false, }; - let context = { + const context = { module: { exports: {} }, diff --git a/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js b/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js index 93091bac29de..c79baab12bd1 100644 --- a/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js @@ -3,7 +3,7 @@ import hoistVariables from "babel-helper-hoist-variables"; import template from "babel-template"; -let buildTemplate = template(` +const buildTemplate = template(` SYSTEM_REGISTER(MODULE_NAME, [SOURCES], function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) { "use strict"; BEFORE_BODY; @@ -16,7 +16,7 @@ let buildTemplate = template(` }); `); -let buildExportAll = template(` +const buildExportAll = template(` for (var KEY in TARGET) { if (KEY !== "default" && KEY !== "__esModule") EXPORT_OBJ[KEY] = TARGET[KEY]; } @@ -26,22 +26,22 @@ let buildExportAll = template(` const TYPE_IMPORT = "Import"; export default function ({ types: t }) { - let IGNORE_REASSIGNMENT_SYMBOL = Symbol(); + const IGNORE_REASSIGNMENT_SYMBOL = Symbol(); - let reassignmentVisitor = { + const reassignmentVisitor = { "AssignmentExpression|UpdateExpression"(path) { if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; - let arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); + const arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); if (!arg.isIdentifier()) return; - let name = arg.node.name; + const name = arg.node.name; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - let exportedNames = this.exports[name]; + const exportedNames = this.exports[name]; if (!exportedNames) return; let node = path.node; @@ -59,7 +59,7 @@ export default function ({ types: t }) { isPostUpdateExpression = false; } - for (let exportedName of exportedNames) { + for (const exportedName of exportedNames) { node = this.buildCall(exportedName, node).expression; } @@ -75,7 +75,7 @@ export default function ({ types: t }) { CallExpression(path, state) { if (path.node.callee.type === TYPE_IMPORT) { - let contextIdent = state.contextIdent; + const contextIdent = state.contextIdent; path.replaceWith(t.callExpression(t.memberExpression(contextIdent, t.identifier("import")), path.node.arguments)); } }, @@ -91,17 +91,17 @@ export default function ({ types: t }) { state.contextIdent = path.scope.generateUidIdentifier("context"); }, exit(path, state) { - let exportIdent = path.scope.generateUidIdentifier("export"); - let contextIdent = state.contextIdent; + const exportIdent = path.scope.generateUidIdentifier("export"); + const contextIdent = state.contextIdent; - let exportNames = Object.create(null); - let modules = []; + const exportNames = Object.create(null); + const modules = []; let beforeBody = []; - let setters = []; - let sources = []; - let variableIds = []; - let removedPaths = []; + const setters = []; + const sources = []; + const variableIds = []; + const removedPaths = []; function addExportName(key, val) { exportNames[key] = exportNames[key] || []; @@ -127,7 +127,7 @@ export default function ({ types: t }) { ); } - let body: Array = path.get("body"); + const body: Array = path.get("body"); let canHoist = true; for (let path of body) { @@ -138,14 +138,14 @@ export default function ({ types: t }) { } } - for (let path of body) { + for (const path of body) { if (canHoist && path.isFunctionDeclaration()) { beforeBody.push(path.node); removedPaths.push(path); } else if (path.isImportDeclaration()) { - let source = path.node.source.value; + const source = path.node.source.value; pushModule(source, "imports", path.node.specifiers); - for (let name in path.getBindingIdentifiers()) { + for (const name in path.getBindingIdentifiers()) { path.scope.removeBinding(name); variableIds.push(t.identifier(name)); } @@ -154,10 +154,10 @@ export default function ({ types: t }) { pushModule(path.node.source.value, "exports", path.node); path.remove(); } else if (path.isExportDefaultDeclaration()) { - let declar = path.get("declaration"); + const declar = path.get("declaration"); if (declar.isClassDeclaration() || declar.isFunctionDeclaration()) { - let id = declar.node.id; - let nodes = []; + const id = declar.node.id; + const nodes = []; if (id) { nodes.push(declar.node); @@ -177,16 +177,16 @@ export default function ({ types: t }) { path.replaceWith(buildExportCall("default", declar.node)); } } else if (path.isExportNamedDeclaration()) { - let declar = path.get("declaration"); + const declar = path.get("declaration"); if (declar.node) { path.replaceWith(declar); - let nodes = []; + const nodes = []; let bindingIdentifiers; if (path.isFunction()) { - let node = declar.node; - let name = node.id.name; + const node = declar.node; + const name = node.id.name; if (canHoist) { addExportName(name, name); beforeBody.push(node); @@ -198,21 +198,21 @@ export default function ({ types: t }) { } else { bindingIdentifiers = declar.getBindingIdentifiers(); } - for (let name in bindingIdentifiers) { + for (const name in bindingIdentifiers) { addExportName(name, name); nodes.push(buildExportCall(name, t.identifier(name))); } path.insertAfter(nodes); } else { - let specifiers = path.node.specifiers; + const specifiers = path.node.specifiers; if (specifiers && specifiers.length) { if (path.node.source) { pushModule(path.node.source.value, "exports", specifiers); path.remove(); } else { - let nodes = []; + const nodes = []; - for (let specifier of specifiers) { + for (const specifier of specifiers) { nodes.push(buildExportCall(specifier.exported.name, specifier.local)); addExportName(specifier.local.name, specifier.exported.name); } @@ -225,8 +225,8 @@ export default function ({ types: t }) { } modules.forEach(function (specifiers) { - let setterBody = []; - let target = path.scope.generateUidIdentifier(specifiers.key); + const setterBody = []; + const target = path.scope.generateUidIdentifier(specifiers.key); for (let specifier of specifiers.imports) { if (t.isImportNamespaceSpecifier(specifier)) { @@ -241,13 +241,13 @@ export default function ({ types: t }) { } if (specifiers.exports.length) { - let exportObjRef = path.scope.generateUidIdentifier("exportObj"); + const exportObjRef = path.scope.generateUidIdentifier("exportObj"); setterBody.push(t.variableDeclaration("var", [ t.variableDeclarator(exportObjRef, t.objectExpression([])) ])); - for (let node of specifiers.exports) { + for (const node of specifiers.exports) { if (t.isExportAllDeclaration(node)) { setterBody.push(buildExportAll({ KEY: path.scope.generateUidIdentifier("key"), @@ -288,7 +288,7 @@ export default function ({ types: t }) { scope: path.scope }); - for (let path of removedPaths) { + for (const path of removedPaths) { path.remove(); } diff --git a/packages/babel-plugin-transform-es2015-modules-umd/src/index.js b/packages/babel-plugin-transform-es2015-modules-umd/src/index.js index 44b88ee55d65..b13ab6af37dd 100644 --- a/packages/babel-plugin-transform-es2015-modules-umd/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-umd/src/index.js @@ -3,18 +3,18 @@ import { basename, extname } from "path"; import template from "babel-template"; -let buildPrerequisiteAssignment = template(` +const buildPrerequisiteAssignment = template(` GLOBAL_REFERENCE = GLOBAL_REFERENCE || {} `); -let buildGlobalExport = template(` +const buildGlobalExport = template(` var mod = { exports: {} }; factory(BROWSER_ARGUMENTS); PREREQUISITE_ASSIGNMENTS GLOBAL_TO_ASSIGN = mod.exports; `); -let buildWrapper = template(` +const buildWrapper = template(` (function (global, factory) { if (typeof define === "function" && define.amd) { define(MODULE_NAME, AMD_ARGUMENTS, factory); @@ -30,11 +30,11 @@ export default function ({ types: t }) { function isValidDefine(path) { if (!path.isExpressionStatement()) return; - let expr = path.get("expression"); + const expr = path.get("expression"); if (!expr.isCallExpression()) return false; if (!expr.get("callee").isIdentifier({ name: "define" })) return false; - let args = expr.get("arguments"); + const args = expr.get("arguments"); if (args.length === 3 && !args.shift().isStringLiteral()) return false; if (args.length !== 2) return false; if (!args.shift().isArrayExpression()) return false; @@ -49,18 +49,18 @@ export default function ({ types: t }) { visitor: { Program: { exit(path, state) { - let last = path.get("body").pop(); + const last = path.get("body").pop(); if (!isValidDefine(last)) return; - let call = last.node.expression; - let args = call.arguments; + const call = last.node.expression; + const args = call.arguments; - let moduleName = args.length === 3 ? args.shift() : null; - let amdArgs = call.arguments[0]; - let func = call.arguments[1]; - let browserGlobals = state.opts.globals || {}; + const moduleName = args.length === 3 ? args.shift() : null; + const amdArgs = call.arguments[0]; + const func = call.arguments[1]; + const browserGlobals = state.opts.globals || {}; - let commonArgs = amdArgs.elements.map((arg) => { + const commonArgs = amdArgs.elements.map((arg) => { if (arg.value === "module" || arg.value === "exports") { return t.identifier(arg.value); } else { @@ -68,7 +68,7 @@ export default function ({ types: t }) { } }); - let browserArgs = amdArgs.elements.map((arg) => { + const browserArgs = amdArgs.elements.map((arg) => { if (arg.value === "module") { return t.identifier("mod"); } else if (arg.value === "exports") { @@ -77,7 +77,7 @@ export default function ({ types: t }) { let memberExpression; if (state.opts.exactGlobals) { - let globalRef = browserGlobals[arg.value]; + const globalRef = browserGlobals[arg.value]; if (globalRef) { memberExpression = globalRef.split(".").reduce( (accum, curr) => t.memberExpression(accum, t.identifier(curr)), t.identifier("global") @@ -88,8 +88,8 @@ export default function ({ types: t }) { ); } } else { - let requireName = basename(arg.value, extname(arg.value)); - let globalName = browserGlobals[requireName] || requireName; + const requireName = basename(arg.value, extname(arg.value)); + const globalName = browserGlobals[requireName] || requireName; memberExpression = t.memberExpression( t.identifier("global"), t.identifier(t.toIdentifier(globalName)) ); @@ -99,19 +99,19 @@ export default function ({ types: t }) { } }); - let moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename; + const moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename; let globalToAssign = t.memberExpression( t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename)) ); let prerequisiteAssignments = null; if (state.opts.exactGlobals) { - let globalName = browserGlobals[moduleNameOrBasename]; + const globalName = browserGlobals[moduleNameOrBasename]; if (globalName) { prerequisiteAssignments = []; - let members = globalName.split("."); + const members = globalName.split("."); globalToAssign = members.slice(1).reduce((accum, curr) => { prerequisiteAssignments.push(buildPrerequisiteAssignment({ GLOBAL_REFERENCE: accum })); return t.memberExpression(accum, t.identifier(curr)); @@ -119,7 +119,7 @@ export default function ({ types: t }) { } } - let globalExport = buildGlobalExport({ + const globalExport = buildGlobalExport({ BROWSER_ARGUMENTS: browserArgs, PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments, GLOBAL_TO_ASSIGN: globalToAssign diff --git a/packages/babel-plugin-transform-es2015-object-super/src/index.js b/packages/babel-plugin-transform-es2015-object-super/src/index.js index 95098fda8a53..5e633fe44728 100644 --- a/packages/babel-plugin-transform-es2015-object-super/src/index.js +++ b/packages/babel-plugin-transform-es2015-object-super/src/index.js @@ -2,7 +2,7 @@ import ReplaceSupers from "babel-helper-replace-supers"; export default function ({ types: t }) { function Property(path, node, scope, getObjectRef, file) { - let replaceSupers = new ReplaceSupers({ + const replaceSupers = new ReplaceSupers({ getObjectRef: getObjectRef, methodNode: node, methodPath: path, @@ -14,12 +14,12 @@ export default function ({ types: t }) { replaceSupers.replace(); } - let CONTAINS_SUPER = Symbol(); + const CONTAINS_SUPER = Symbol(); return { visitor: { Super(path) { - let parentObj = path.findParent((path) => path.isObjectExpression()); + const parentObj = path.findParent((path) => path.isObjectExpression()); if (parentObj) parentObj.node[CONTAINS_SUPER] = true; }, @@ -28,9 +28,9 @@ export default function ({ types: t }) { if (!path.node[CONTAINS_SUPER]) return; let objectRef; - let getObjectRef = () => objectRef = objectRef || path.scope.generateUidIdentifier("obj"); + const getObjectRef = () => objectRef = objectRef || path.scope.generateUidIdentifier("obj"); - let propPaths: Array = path.get("properties"); + const propPaths: Array = path.get("properties"); for (let propPath of propPaths) { if (propPath.isObjectProperty()) propPath = propPath.get("value"); Property(propPath, propPath.node, path.scope, getObjectRef, file); diff --git a/packages/babel-plugin-transform-es2015-parameters/src/default.js b/packages/babel-plugin-transform-es2015-parameters/src/default.js index 445000fadba6..f123ed195ef8 100644 --- a/packages/babel-plugin-transform-es2015-parameters/src/default.js +++ b/packages/babel-plugin-transform-es2015-parameters/src/default.js @@ -5,7 +5,7 @@ import callDelegate from "babel-helper-call-delegate"; import template from "babel-template"; import * as t from "babel-types"; -let buildDefaultParam = template(` +const buildDefaultParam = template(` let VARIABLE_NAME = ARGUMENTS.length > ARGUMENT_KEY && ARGUMENTS[ARGUMENT_KEY] !== undefined ? ARGUMENTS[ARGUMENT_KEY] @@ -13,12 +13,12 @@ let buildDefaultParam = template(` DEFAULT_VALUE; `); -let buildCutOff = template(` +const buildCutOff = template(` let $0 = $1[$2]; `); function hasDefaults(node) { - for (let param of (node.params: Array)) { + for (const param of (node.params: Array)) { if (!t.isIdentifier(param)) return true; } return false; @@ -30,7 +30,7 @@ function isSafeBinding(scope, node) { return kind === "param" || kind === "local"; } -let iifeVisitor = { +const iifeVisitor = { ReferencedIdentifier(path, state) { const { scope, node } = path; if (node.name === "eval" || !isSafeBinding(scope, node)) { @@ -45,23 +45,23 @@ let iifeVisitor = { } }; -export let visitor = { +export const visitor = { Function(path) { - let { node, scope } = path; + const { node, scope } = path; if (!hasDefaults(node)) return; // ensure it's a block, useful for arrow functions path.ensureBlock(); - let state = { + const state = { iife: false, scope: scope }; - let body = []; + const body = []; // - let argsIdentifier = t.identifier("arguments"); + const argsIdentifier = t.identifier("arguments"); argsIdentifier._shadowedFunctionLiteral = path; // push a default parameter definition @@ -77,12 +77,12 @@ export let visitor = { } // - let lastNonDefaultParam = getFunctionArity(node); + const lastNonDefaultParam = getFunctionArity(node); // - let params = path.get("params"); + const params = path.get("params"); for (let i = 0; i < params.length; i++) { - let param = params[i]; + const param = params[i]; if (!param.isAssignmentPattern()) { if (!state.iife && !param.isIdentifier()) { @@ -92,12 +92,12 @@ export let visitor = { continue; } - let left = param.get("left"); - let right = param.get("right"); + const left = param.get("left"); + const right = param.get("right"); // if (i >= lastNonDefaultParam || left.isPattern()) { - let placeholder = scope.generateUidIdentifier("x"); + const placeholder = scope.generateUidIdentifier("x"); placeholder._isDefaultPlaceholder = true; node.params[i] = placeholder; } else { @@ -119,10 +119,10 @@ export let visitor = { // add declarations for trailing parameters for (let i = lastNonDefaultParam + 1; i < node.params.length; i++) { - let param = node.params[i]; + const param = node.params[i]; if (param._isDefaultPlaceholder) continue; - let declar = buildCutOff(param, argsIdentifier, t.numericLiteral(i)); + const declar = buildCutOff(param, argsIdentifier, t.numericLiteral(i)); declar._blockHoist = node.params.length - i; body.push(declar); } diff --git a/packages/babel-plugin-transform-es2015-parameters/src/destructuring.js b/packages/babel-plugin-transform-es2015-parameters/src/destructuring.js index e3a7e10494ac..495ac0605092 100644 --- a/packages/babel-plugin-transform-es2015-parameters/src/destructuring.js +++ b/packages/babel-plugin-transform-es2015-parameters/src/destructuring.js @@ -1,20 +1,20 @@ import * as t from "babel-types"; -export let visitor = { +export const visitor = { Function(path) { - let params: Array = path.get("params"); + const params: Array = path.get("params"); // If there's a rest param, no need to loop through it. Also, we need to // hoist one more level to get `declar` at the right spot. - let hoistTweak = t.isRestElement(params[params.length - 1]) ? 1 : 0; - let outputParamsLength = params.length - hoistTweak; + const hoistTweak = t.isRestElement(params[params.length - 1]) ? 1 : 0; + const outputParamsLength = params.length - hoistTweak; for (let i = 0; i < outputParamsLength; i++) { - let param = params[i]; + const param = params[i]; if (param.isArrayPattern() || param.isObjectPattern()) { - let uid = path.scope.generateUidIdentifier("ref"); + const uid = path.scope.generateUidIdentifier("ref"); - let declar = t.variableDeclaration("let", [ + const declar = t.variableDeclaration("let", [ t.variableDeclarator(param.node, uid) ]); declar._blockHoist = outputParamsLength - i; diff --git a/packages/babel-plugin-transform-es2015-parameters/src/index.js b/packages/babel-plugin-transform-es2015-parameters/src/index.js index 6279147062ba..d59d21b3bf60 100644 --- a/packages/babel-plugin-transform-es2015-parameters/src/index.js +++ b/packages/babel-plugin-transform-es2015-parameters/src/index.js @@ -10,8 +10,8 @@ export default function () { visitor: visitors.merge([{ ArrowFunctionExpression(path) { // default/rest visitors require access to `arguments` - let params: Array = path.get("params"); - for (let param of params) { + const params: Array = path.get("params"); + for (const param of params) { if (param.isRestElement() || param.isAssignmentPattern()) { path.arrowFunctionToShadowed(); break; diff --git a/packages/babel-plugin-transform-es2015-parameters/src/rest.js b/packages/babel-plugin-transform-es2015-parameters/src/rest.js index bda77d8c11e1..3ae51ed5488b 100644 --- a/packages/babel-plugin-transform-es2015-parameters/src/rest.js +++ b/packages/babel-plugin-transform-es2015-parameters/src/rest.js @@ -3,7 +3,7 @@ import template from "babel-template"; import * as t from "babel-types"; -let buildRest = template(` +const buildRest = template(` for (var LEN = ARGUMENTS.length, ARRAY = Array(ARRAY_LEN), KEY = START; @@ -13,19 +13,19 @@ let buildRest = template(` } `); -let restIndex = template(` +const restIndex = template(` ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX] `); -let restIndexImpure = template(` +const restIndexImpure = template(` REF = INDEX, ARGUMENTS.length <= REF ? undefined : ARGUMENTS[REF] `); -let restLength = template(` +const restLength = template(` ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET `); -let memberExpressionOptimisationVisitor = { +const memberExpressionOptimisationVisitor = { Scope(path, state) { // check if this scope has a local binding that will shadow the rest parameter if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { @@ -43,7 +43,7 @@ let memberExpressionOptimisationVisitor = { "Function|ClassProperty": function (path, state) { // Detect whether any reference to rest is contained in nested functions to // determine if deopt is necessary. - let oldNoOptimise = state.noOptimise; + const oldNoOptimise = state.noOptimise; state.noOptimise = true; path.traverse(memberExpressionOptimisationVisitor, state); state.noOptimise = oldNoOptimise; @@ -54,7 +54,7 @@ let memberExpressionOptimisationVisitor = { }, ReferencedIdentifier(path, state) { - let { node } = path; + const { node } = path; // we can't guarantee the purity of arguments if (node.name === "arguments") { @@ -67,7 +67,7 @@ let memberExpressionOptimisationVisitor = { if (state.noOptimise) { state.deopted = true; } else { - let {parentPath} = path; + const {parentPath} = path; // Is this identifier the right hand side of a default parameter? if (parentPath.listKey === "params" && parentPath.key < state.offset) { @@ -77,9 +77,9 @@ let memberExpressionOptimisationVisitor = { // ex: `args[0]` // ex: `args.whatever` if (parentPath.isMemberExpression({ object: node })) { - let grandparentPath = parentPath.parentPath; + const grandparentPath = parentPath.parentPath; - let argsOptEligible = !state.deopted && !( + const argsOptEligible = !state.deopted && !( // ex: `args[0] = "whatever"` ( grandparentPath.isAssignmentExpression() && @@ -134,7 +134,7 @@ let memberExpressionOptimisationVisitor = { // optimise single spread args in calls // ex: fn(...args) if (state.offset === 0 && parentPath.isSpreadElement()) { - let call = parentPath.parentPath; + const call = parentPath.parentPath; if (call.isCallExpression() && call.node.arguments.length === 1) { state.candidates.push({cause: "argSpread", path}); return; @@ -175,7 +175,7 @@ function optimiseIndexGetter(path, argsId, offset) { const { scope } = path; if (!scope.isPure(index)) { - let temp = scope.generateUidIdentifierBasedOnNode(index); + const temp = scope.generateUidIdentifierBasedOnNode(index); scope.push({id: temp, kind: "var"}); path.parentPath.replaceWith(restIndexImpure({ ARGUMENTS: argsId, @@ -201,20 +201,20 @@ function optimiseLengthGetter(path, argsId, offset) { } } -export let visitor = { +export const visitor = { Function(path) { - let { node, scope } = path; + const { node, scope } = path; if (!hasRest(node)) return; - let rest = node.params.pop().argument; + const rest = node.params.pop().argument; - let argsId = t.identifier("arguments"); + const argsId = t.identifier("arguments"); // otherwise `arguments` will be remapped in arrow functions argsId._shadowedFunctionLiteral = path; // check and optimise for extremely common cases - let state = { + const state = { references: [], offset: node.params.length, @@ -246,7 +246,7 @@ export let visitor = { // There are only "shorthand" references if (!state.deopted && !state.references.length) { - for (let {path, cause} of (state.candidates: Array)) { + for (const {path, cause} of (state.candidates: Array)) { switch (cause) { case "indexGetter": optimiseIndexGetter(path, argsId, state.offset); @@ -268,9 +268,9 @@ export let visitor = { // deopt shadowed functions as transforms like regenerator may try touch the allocation loop state.deopted = state.deopted || !!node.shadow; - let start = t.numericLiteral(node.params.length); - let key = scope.generateUidIdentifier("key"); - let len = scope.generateUidIdentifier("len"); + const start = t.numericLiteral(node.params.length); + const key = scope.generateUidIdentifier("key"); + const len = scope.generateUidIdentifier("len"); let arrKey = key; let arrLen = len; @@ -293,7 +293,7 @@ export let visitor = { ); } - let loop = buildRest({ + const loop = buildRest({ ARGUMENTS: argsId, ARRAY_KEY: arrKey, ARRAY_LEN: arrLen, diff --git a/packages/babel-plugin-transform-es2015-shorthand-properties/src/index.js b/packages/babel-plugin-transform-es2015-shorthand-properties/src/index.js index c3aa80e4f5b9..3bc612ab0e5b 100644 --- a/packages/babel-plugin-transform-es2015-shorthand-properties/src/index.js +++ b/packages/babel-plugin-transform-es2015-shorthand-properties/src/index.js @@ -4,7 +4,7 @@ export default function () { return { visitor: { ObjectMethod(path) { - let { node } = path; + const { node } = path; if (node.kind === "method") { const func = t.functionExpression(null, node.params, node.body, node.generator, node.async); func.returnType = node.returnType; diff --git a/packages/babel-plugin-transform-es2015-spread/src/index.js b/packages/babel-plugin-transform-es2015-spread/src/index.js index d7768cb16129..14dfd5249249 100644 --- a/packages/babel-plugin-transform-es2015-spread/src/index.js +++ b/packages/babel-plugin-transform-es2015-spread/src/index.js @@ -17,7 +17,7 @@ export default function ({ types: t }) { } function build(props: Array, scope, state) { - let nodes = []; + const nodes = []; let _props = []; @@ -27,7 +27,7 @@ export default function ({ types: t }) { _props = []; } - for (let prop of props) { + for (const prop of props) { if (t.isSpreadElement(prop)) { push(); nodes.push(getSpreadLiteral(prop, scope, state)); @@ -44,11 +44,11 @@ export default function ({ types: t }) { return { visitor: { ArrayExpression(path, state) { - let { node, scope } = path; - let elements = node.elements; + const { node, scope } = path; + const elements = node.elements; if (!hasSpread(elements)) return; - let nodes = build(elements, scope, state); + const nodes = build(elements, scope, state); let first = nodes.shift(); if (!t.isArrayExpression(first)) { @@ -60,12 +60,12 @@ export default function ({ types: t }) { }, CallExpression(path, state) { - let { node, scope } = path; + const { node, scope } = path; - let args = node.arguments; + const args = node.arguments; if (!hasSpread(args)) return; - let calleePath = path.get("callee"); + const calleePath = path.get("callee"); if (calleePath.isSuper()) return; let contextLiteral = t.identifier("undefined"); @@ -79,17 +79,17 @@ export default function ({ types: t }) { nodes = build(args, scope, state); } - let first = nodes.shift(); + const first = nodes.shift(); if (nodes.length) { node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); } else { node.arguments.push(first); } - let callee = node.callee; + const callee = node.callee; if (calleePath.isMemberExpression()) { - let temp = scope.maybeGenerateMemoised(callee.object); + const temp = scope.maybeGenerateMemoised(callee.object); if (temp) { callee.object = t.assignmentExpression("=", temp, callee.object); contextLiteral = temp; @@ -109,13 +109,13 @@ export default function ({ types: t }) { }, NewExpression(path, state) { - let { node, scope } = path; + const { node, scope } = path; let args = node.arguments; if (!hasSpread(args)) return; - let nodes = build(args, scope, state); + const nodes = build(args, scope, state); - let context = t.arrayExpression([t.nullLiteral()]); + const context = t.arrayExpression([t.nullLiteral()]); args = t.callExpression(t.memberExpression(context, t.identifier("concat")), nodes); diff --git a/packages/babel-plugin-transform-es2015-sticky-regex/src/index.js b/packages/babel-plugin-transform-es2015-sticky-regex/src/index.js index 8b703e85c810..409b6d9027d4 100644 --- a/packages/babel-plugin-transform-es2015-sticky-regex/src/index.js +++ b/packages/babel-plugin-transform-es2015-sticky-regex/src/index.js @@ -5,7 +5,7 @@ export default function () { return { visitor: { RegExpLiteral(path) { - let { node } = path; + const { node } = path; if (!regex.is(node, "y")) return; path.replaceWith(t.newExpression(t.identifier("RegExp"), [ diff --git a/packages/babel-plugin-transform-es2015-template-literals/src/index.js b/packages/babel-plugin-transform-es2015-template-literals/src/index.js index 7359598f9982..40d3a4d24b31 100644 --- a/packages/babel-plugin-transform-es2015-template-literals/src/index.js +++ b/packages/babel-plugin-transform-es2015-template-literals/src/index.js @@ -10,14 +10,14 @@ export default function ({ types: t }) { return { visitor: { TaggedTemplateExpression(path, state) { - let { node } = path; - let quasi = node.quasi; + const { node } = path; + const quasi = node.quasi; let args = []; let strings = []; let raw = []; - for (let elem of (quasi.quasis: Array)) { + for (const elem of (quasi.quasis: Array)) { strings.push(t.stringLiteral(elem.value.cooked)); raw.push(t.stringLiteral(elem.value.raw)); } @@ -28,7 +28,7 @@ export default function ({ types: t }) { let templateName = "taggedTemplateLiteral"; if (state.opts.loose) templateName += "Loose"; - let templateObject = state.file.addTemplateObject(templateName, strings, raw); + const templateObject = state.file.addTemplateObject(templateName, strings, raw); args.push(templateObject); args = args.concat(quasi.expressions); @@ -39,12 +39,12 @@ export default function ({ types: t }) { TemplateLiteral(path, state) { let nodes: Array = []; - let expressions = path.get("expressions"); + const expressions = path.get("expressions"); - for (let elem of (path.node.quasis: Array)) { + for (const elem of (path.node.quasis: Array)) { nodes.push(t.stringLiteral(elem.value.cooked)); - let expr = expressions.shift(); + const expr = expressions.shift(); if (expr) { if (state.opts.spec && !expr.isBaseType("string") && !expr.isBaseType("number")) { nodes.push(t.callExpression(t.identifier("String"), [expr.node])); @@ -66,7 +66,7 @@ export default function ({ types: t }) { if (nodes.length > 1) { let root = buildBinaryExpression(nodes.shift(), nodes.shift()); - for (let node of nodes) { + for (const node of nodes) { root = buildBinaryExpression(root, node); } diff --git a/packages/babel-plugin-transform-es2015-typeof-symbol/src/index.js b/packages/babel-plugin-transform-es2015-typeof-symbol/src/index.js index b2291af302f9..4cea5acd1a5e 100644 --- a/packages/babel-plugin-transform-es2015-typeof-symbol/src/index.js +++ b/packages/babel-plugin-transform-es2015-typeof-symbol/src/index.js @@ -1,7 +1,7 @@ /* eslint max-len: 0 */ export default function ({ types: t }) { - let IGNORE = Symbol(); + const IGNORE = Symbol(); return { visitor: { @@ -14,23 +14,23 @@ export default function ({ types: t }) { }, UnaryExpression(path) { - let { node, parent } = path; + const { node, parent } = path; if (node[IGNORE]) return; if (path.find((path) => path.node && !!path.node._generated)) return; if (path.parentPath.isBinaryExpression() && t.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { // optimise `typeof foo === "string"` since we can determine that they'll never need to handle symbols - let opposite = path.getOpposite(); + const opposite = path.getOpposite(); if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") { return; } } if (node.operator === "typeof") { - let call = t.callExpression(this.addHelper("typeof"), [node.argument]); + const call = t.callExpression(this.addHelper("typeof"), [node.argument]); if (path.get("argument").isIdentifier()) { - let undefLiteral = t.stringLiteral("undefined"); - let unary = t.unaryExpression("typeof", node.argument); + const undefLiteral = t.stringLiteral("undefined"); + const unary = t.unaryExpression("typeof", node.argument); unary[IGNORE] = true; path.replaceWith(t.conditionalExpression( t.binaryExpression("===", unary, undefLiteral), diff --git a/packages/babel-plugin-transform-es3-member-expression-literals/src/index.js b/packages/babel-plugin-transform-es3-member-expression-literals/src/index.js index fa78563a2348..2aa02f12083f 100644 --- a/packages/babel-plugin-transform-es3-member-expression-literals/src/index.js +++ b/packages/babel-plugin-transform-es3-member-expression-literals/src/index.js @@ -3,7 +3,7 @@ export default function ({ types: t }) { visitor: { MemberExpression: { exit({ node }) { - let prop = node.property; + const prop = node.property; if (!node.computed && t.isIdentifier(prop) && !t.isValidIdentifier(prop.name)) { // foo.default -> foo["default"] node.property = t.stringLiteral(prop.name); diff --git a/packages/babel-plugin-transform-es3-property-literals/src/index.js b/packages/babel-plugin-transform-es3-property-literals/src/index.js index b8f6f412c2b8..e62a88f8ee27 100644 --- a/packages/babel-plugin-transform-es3-property-literals/src/index.js +++ b/packages/babel-plugin-transform-es3-property-literals/src/index.js @@ -3,7 +3,7 @@ export default function ({ types: t }) { visitor: { ObjectProperty: { exit({node}) { - let key = node.key; + const key = node.key; if (!node.computed && t.isIdentifier(key) && !t.isValidIdentifier(key.name)) { // default: "bar" -> "default": "bar" node.key = t.stringLiteral(key.name); diff --git a/packages/babel-plugin-transform-es5-property-mutators/src/index.js b/packages/babel-plugin-transform-es5-property-mutators/src/index.js index 46d810f6f55a..83727bb0a59a 100644 --- a/packages/babel-plugin-transform-es5-property-mutators/src/index.js +++ b/packages/babel-plugin-transform-es5-property-mutators/src/index.js @@ -4,9 +4,9 @@ export default function ({ types: t }) { return { visitor: { ObjectExpression(path, file) { - let { node } = path; + const { node } = path; let hasAny = false; - for (let prop of (node.properties: Array)) { + for (const prop of (node.properties: Array)) { if (prop.kind === "get" || prop.kind === "set") { hasAny = true; break; @@ -14,7 +14,7 @@ export default function ({ types: t }) { } if (!hasAny) return; - let mutatorMap = {}; + const mutatorMap = {}; node.properties = node.properties.filter(function (prop) { if (!prop.computed && (prop.kind === "get" || prop.kind === "set")) { diff --git a/packages/babel-plugin-transform-eval/src/index.js b/packages/babel-plugin-transform-eval/src/index.js index 677401057a40..ec92ec40f262 100644 --- a/packages/babel-plugin-transform-eval/src/index.js +++ b/packages/babel-plugin-transform-eval/src/index.js @@ -3,13 +3,13 @@ export default function ({ parse, traverse }) { visitor: { CallExpression(path) { if (path.get("callee").isIdentifier({ name: "eval" }) && path.node.arguments.length === 1) { - let evaluate = path.get("arguments")[0].evaluate(); + const evaluate = path.get("arguments")[0].evaluate(); if (!evaluate.confident) return; - let code = evaluate.value; + const code = evaluate.value; if (typeof code !== "string") return; - let ast = parse(code); + const ast = parse(code); traverse.removeProperties(ast); return ast.program; } diff --git a/packages/babel-plugin-transform-export-extensions/src/index.js b/packages/babel-plugin-transform-export-extensions/src/index.js index 6b0afad0ceb7..5951b9e42d91 100644 --- a/packages/babel-plugin-transform-export-extensions/src/index.js +++ b/packages/babel-plugin-transform-export-extensions/src/index.js @@ -1,10 +1,10 @@ export default function ({ types: t }) { function build(node, nodes, scope) { - let first = node.specifiers[0]; + const first = node.specifiers[0]; if (!t.isExportNamespaceSpecifier(first) && !t.isExportDefaultSpecifier(first)) return; - let specifier = node.specifiers.shift(); - let uid = scope.generateUidIdentifier(specifier.exported.name); + const specifier = node.specifiers.shift(); + const uid = scope.generateUidIdentifier(specifier.exported.name); let newSpecifier; if (t.isExportNamespaceSpecifier(specifier)) { @@ -24,8 +24,8 @@ export default function ({ types: t }) { visitor: { ExportNamedDeclaration(path) { - let { node, scope } = path; - let nodes = []; + const { node, scope } = path; + const nodes = []; build(node, nodes, scope); if (!nodes.length) return; diff --git a/packages/babel-plugin-transform-flow-comments/src/index.js b/packages/babel-plugin-transform-flow-comments/src/index.js index ece00a024a1c..8abf61aa41cf 100644 --- a/packages/babel-plugin-transform-flow-comments/src/index.js +++ b/packages/babel-plugin-transform-flow-comments/src/index.js @@ -16,14 +16,14 @@ export default function ({ types: t }) { visitor: { TypeCastExpression(path) { - let { node } = path; + const { node } = path; path.get("expression").addComment("trailing", generateComment(path.get("typeAnnotation"))); path.replaceWith(t.parenthesizedExpression(node.expression)); }, // support function a(b?) {} Identifier(path) { - let { node } = path; + const { node } = path; if (!node.optional || node.typeAnnotation) { return; } @@ -45,13 +45,13 @@ export default function ({ types: t }) { // support for `class X { foo: string }` - #4622 ClassProperty(path) { - let { node, parent } = path; + const { node, parent } = path; if (!node.value) wrapInFlowComment(path, parent); }, // support `export type a = {}` - #8 Error: You passed path.replaceWith() a falsy node "ExportNamedDeclaration|Flow"(path) { - let { node, parent } = path; + const { node, parent } = path; if (t.isExportNamedDeclaration(node) && !t.isFlow(node.declaration)) { return; } @@ -60,7 +60,7 @@ export default function ({ types: t }) { // support `import type A` and `import typeof A` #10 ImportDeclaration(path) { - let { node, parent } = path; + const { node, parent } = path; if (t.isImportDeclaration(node) && node.importKind !== "type" && node.importKind !== "typeof") { return; } diff --git a/packages/babel-plugin-transform-flow-strip-types/src/index.js b/packages/babel-plugin-transform-flow-strip-types/src/index.js index c64abb9a52fe..4b080f92580a 100644 --- a/packages/babel-plugin-transform-flow-strip-types/src/index.js +++ b/packages/babel-plugin-transform-flow-strip-types/src/index.js @@ -6,7 +6,7 @@ export default function ({ types: t }) { visitor: { Program(path, { file: { ast: { comments } } }) { - for (let comment of (comments: Array)) { + for (const comment of (comments: Array)) { if (comment.value.indexOf(FLOW_DIRECTIVE) >= 0) { // remove flow directive comment.value = comment.value.replace(FLOW_DIRECTIVE, ""); @@ -46,7 +46,7 @@ export default function ({ types: t }) { Function({ node }) { for (let i = 0; i < node.params.length; i++) { - let param = node.params[i]; + const param = node.params[i]; param.optional = false; } }, diff --git a/packages/babel-plugin-transform-function-bind/src/index.js b/packages/babel-plugin-transform-function-bind/src/index.js index 0d3099930f53..27c20faa1e36 100644 --- a/packages/babel-plugin-transform-function-bind/src/index.js +++ b/packages/babel-plugin-transform-function-bind/src/index.js @@ -8,15 +8,15 @@ export default function ({ types: t }) { } function getStaticContext(bind, scope) { - let object = bind.object || bind.callee.object; + const object = bind.object || bind.callee.object; return scope.isStatic(object) && object; } function inferBindContext(bind, scope) { - let staticContext = getStaticContext(bind, scope); + const staticContext = getStaticContext(bind, scope); if (staticContext) return staticContext; - let tempId = getTempId(scope); + const tempId = getTempId(scope); if (bind.object) { bind.callee = t.sequenceExpression([ t.assignmentExpression("=", tempId, bind.object), @@ -33,17 +33,17 @@ export default function ({ types: t }) { visitor: { CallExpression({ node, scope }) { - let bind = node.callee; + const bind = node.callee; if (!t.isBindExpression(bind)) return; - let context = inferBindContext(bind, scope); + const context = inferBindContext(bind, scope); node.callee = t.memberExpression(bind.callee, t.identifier("call")); node.arguments.unshift(context); }, BindExpression(path) { - let { node, scope } = path; - let context = inferBindContext(node, scope); + const { node, scope } = path; + const context = inferBindContext(node, scope); path.replaceWith(t.callExpression(t.memberExpression(node.callee, t.identifier("bind")), [context])); } } diff --git a/packages/babel-plugin-transform-jscript/src/index.js b/packages/babel-plugin-transform-jscript/src/index.js index 1361821acf05..87f83c2bedeb 100644 --- a/packages/babel-plugin-transform-jscript/src/index.js +++ b/packages/babel-plugin-transform-jscript/src/index.js @@ -3,7 +3,7 @@ export default function ({ types: t }) { visitor: { FunctionExpression: { exit(path) { - let { node } = path; + const { node } = path; if (!node.id) return; node._ignoreUserWhitespace = true; diff --git a/packages/babel-plugin-transform-object-rest-spread/src/index.js b/packages/babel-plugin-transform-object-rest-spread/src/index.js index dbc357be07d9..b705529236b4 100644 --- a/packages/babel-plugin-transform-object-rest-spread/src/index.js +++ b/packages/babel-plugin-transform-object-rest-spread/src/index.js @@ -11,7 +11,7 @@ export default function ({ types: t }) { } function hasSpread(node) { - for (let prop of (node.properties)) { + for (const prop of (node.properties)) { if (t.isSpreadProperty(prop)) { return true; } @@ -22,8 +22,8 @@ export default function ({ types: t }) { function createObjectSpread(file, props, objRef) { const restProperty = props.pop(); - let keys = []; - for (let prop of props) { + const keys = []; + for (const prop of props) { let key = prop.key; if (t.isIdentifier(key) && !prop.computed) { key = t.stringLiteral(prop.key.name); @@ -44,10 +44,10 @@ export default function ({ types: t }) { function replaceRestProperty(paramsPath, i, numParams) { if (paramsPath.isObjectPattern() && hasRestProperty(paramsPath)) { - let parentPath = paramsPath.parentPath; - let uid = parentPath.scope.generateUidIdentifier("ref"); + const parentPath = paramsPath.parentPath; + const uid = parentPath.scope.generateUidIdentifier("ref"); - let declar = t.variableDeclaration("let", [ + const declar = t.variableDeclaration("let", [ t.variableDeclarator(paramsPath.node, uid) ]); declar._blockHoist = i ? numParams - i : 1; @@ -65,7 +65,7 @@ export default function ({ types: t }) { // taken from transform-es2015-parameters/src/destructuring.js // function a({ b, ...c }) {} Function(path) { - let params = path.get("params"); + const params = path.get("params"); for (let i = 0; i < params.length; i++) { replaceRestProperty(params[i], i, params.length); } @@ -75,7 +75,7 @@ export default function ({ types: t }) { VariableDeclarator(path, file) { if (!path.get("id").isObjectPattern()) { return; } const kind = path.parentPath.node.kind; - let nodes = []; + const nodes = []; path.traverse({ RestProperty(path) { @@ -89,7 +89,7 @@ export default function ({ types: t }) { } }); - let [ argument, callExpression ] = createObjectSpread( + const [ argument, callExpression ] = createObjectSpread( file, path.parentPath.node.properties, ref @@ -108,7 +108,7 @@ export default function ({ types: t }) { ).remove(); } } - },{ + }, { originalPath: path }); @@ -122,14 +122,14 @@ export default function ({ types: t }) { // taken from transform-es2015-destructuring/src/index.js#visitor // export var { a, ...b } = c; ExportNamedDeclaration(path) { - let declaration = path.get("declaration"); + const declaration = path.get("declaration"); if (!declaration.isVariableDeclaration()) return; if (!hasRestProperty(declaration)) return; - let specifiers = []; + const specifiers = []; - for (let name in path.getOuterBindingIdentifiers(path)) { - let id = t.identifier(name); + for (const name in path.getOuterBindingIdentifiers(path)) { + const id = t.identifier(name); specifiers.push(t.exportSpecifier(id, id)); } @@ -145,9 +145,9 @@ export default function ({ types: t }) { }, // ({a, ...b} = c); AssignmentExpression(path, file) { - let leftPath = path.get("left"); + const leftPath = path.get("left"); if (leftPath.isObjectPattern() && hasRestProperty(leftPath)) { - let nodes = []; + const nodes = []; let ref; if (path.isCompletionRecord() || path.parentPath.isExpressionStatement()) { @@ -158,13 +158,13 @@ export default function ({ types: t }) { ])); } - let [ argument, callExpression ] = createObjectSpread( + const [ argument, callExpression ] = createObjectSpread( file, path.node.left.properties, ref ); - let nodeWithoutSpread = t.clone(path.node); + const nodeWithoutSpread = t.clone(path.node); nodeWithoutSpread.right = ref; nodes.push(t.expressionStatement(nodeWithoutSpread)); nodes.push(t.toStatement(t.assignmentExpression( @@ -182,13 +182,13 @@ export default function ({ types: t }) { }, // taken from transform-es2015-destructuring/src/index.js#visitor ForXStatement(path) { - let { node, scope } = path; - let leftPath = path.get("left"); - let left = node.left; + const { node, scope } = path; + const leftPath = path.get("left"); + const left = node.left; // for ({a, ...b} of []) {} if (t.isObjectPattern(left) && hasRestProperty(leftPath)) { - let temp = scope.generateUidIdentifier("ref"); + const temp = scope.generateUidIdentifier("ref"); node.left = t.variableDeclaration("var", [ t.variableDeclarator(temp) @@ -205,10 +205,10 @@ export default function ({ types: t }) { if (!t.isVariableDeclaration(left)) return; - let pattern = left.declarations[0].id; + const pattern = left.declarations[0].id; if (!t.isObjectPattern(pattern)) return; - let key = scope.generateUidIdentifier("ref"); + const key = scope.generateUidIdentifier("ref"); node.left = t.variableDeclaration(left.kind, [ t.variableDeclarator(key, null) ]); @@ -225,12 +225,12 @@ export default function ({ types: t }) { ObjectExpression(path, file) { if (!hasSpread(path.node)) return; - let useBuiltIns = file.opts.useBuiltIns || false; + const useBuiltIns = file.opts.useBuiltIns || false; if (typeof useBuiltIns !== "boolean") { throw new Error("transform-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"); } - let args = []; + const args = []; let props = []; function push() { @@ -239,7 +239,7 @@ export default function ({ types: t }) { props = []; } - for (let prop of (path.node.properties: Array)) { + for (const prop of (path.node.properties: Array)) { if (t.isSpreadProperty(prop)) { push(); args.push(prop.argument); diff --git a/packages/babel-plugin-transform-proto-to-assign/src/index.js b/packages/babel-plugin-transform-proto-to-assign/src/index.js index d17f857c187d..41b0ff442d4a 100644 --- a/packages/babel-plugin-transform-proto-to-assign/src/index.js +++ b/packages/babel-plugin-transform-proto-to-assign/src/index.js @@ -8,7 +8,7 @@ export default function ({ types: t }) { } function isProtoAssignmentExpression(node) { - let left = node.left; + const left = node.left; return t.isMemberExpression(left) && t.isLiteral(t.toComputedKey(left, left.property), { value: "__proto__" }); } @@ -21,9 +21,9 @@ export default function ({ types: t }) { AssignmentExpression(path, file) { if (!isProtoAssignmentExpression(path.node)) return; - let nodes = []; - let left = path.node.left.object; - let temp = path.scope.maybeGenerateMemoised(left); + const nodes = []; + const left = path.node.left.object; + const temp = path.scope.maybeGenerateMemoised(left); if (temp) nodes.push(t.expressionStatement(t.assignmentExpression("=", temp, left))); nodes.push(buildDefaultsCallExpression(path.node, temp || left, file)); @@ -33,7 +33,7 @@ export default function ({ types: t }) { }, ExpressionStatement(path, file) { - let expr = path.node.expression; + const expr = path.node.expression; if (!t.isAssignmentExpression(expr, { operator: "=" })) return; if (isProtoAssignmentExpression(expr)) { @@ -43,9 +43,9 @@ export default function ({ types: t }) { ObjectExpression(path, file) { let proto; - let { node } = path; + const { node } = path; - for (let prop of (node.properties: Array)) { + for (const prop of (node.properties: Array)) { if (isProtoKey(prop)) { proto = prop.value; pull(node.properties, prop); @@ -53,7 +53,7 @@ export default function ({ types: t }) { } if (proto) { - let args = [t.objectExpression([]), proto]; + const args = [t.objectExpression([]), proto]; if (node.properties.length) args.push(node); path.replaceWith(t.callExpression(file.addHelper("extends"), args)); } diff --git a/packages/babel-plugin-transform-react-constant-elements/src/index.js b/packages/babel-plugin-transform-react-constant-elements/src/index.js index 9673af7c2683..a25fb67e6c6d 100644 --- a/packages/babel-plugin-transform-react-constant-elements/src/index.js +++ b/packages/babel-plugin-transform-react-constant-elements/src/index.js @@ -1,7 +1,7 @@ export default function () { - let immutabilityVisitor = { + const immutabilityVisitor = { enter(path, state) { - let stop = () => { + const stop = () => { state.isImmutable = false; path.stop(); }; @@ -28,7 +28,7 @@ export default function () { JSXElement(path) { if (path.node._hoisted) return; - let state = { isImmutable: true }; + const state = { isImmutable: true }; path.traverse(immutabilityVisitor, state); if (state.isImmutable) { diff --git a/packages/babel-plugin-transform-react-display-name/src/index.js b/packages/babel-plugin-transform-react-display-name/src/index.js index 43206810e7e9..ce73d4db74a3 100644 --- a/packages/babel-plugin-transform-react-display-name/src/index.js +++ b/packages/babel-plugin-transform-react-display-name/src/index.js @@ -2,12 +2,12 @@ import path from "path"; export default function ({ types: t }) { function addDisplayName(id, call) { - let props = call.arguments[0].properties; + const props = call.arguments[0].properties; let safe = true; for (let i = 0; i < props.length; i++) { - let prop = props[i]; - let key = t.toComputedKey(prop); + const prop = props[i]; + const key = t.toComputedKey(prop); if (t.isLiteral(key, { value: "displayName" })) { safe = false; break; @@ -19,7 +19,7 @@ export default function ({ types: t }) { } } - let isCreateClassCallExpression = t.buildMatchMemberExpression("React.createClass"); + const isCreateClassCallExpression = t.buildMatchMemberExpression("React.createClass"); function isCreateClass(node) { if (!node || !t.isCallExpression(node)) return false; @@ -28,11 +28,11 @@ export default function ({ types: t }) { if (!isCreateClassCallExpression(node.callee)) return false; // no call arguments - let args = node.arguments; + const args = node.arguments; if (args.length !== 1) return false; // first node arg is not an object - let first = args[0]; + const first = args[0]; if (!t.isObjectExpression(first)) return false; return true; @@ -54,7 +54,7 @@ export default function ({ types: t }) { }, CallExpression(path) { - let { node } = path; + const { node } = path; if (!isCreateClass(node)) return; let id; diff --git a/packages/babel-plugin-transform-react-inline-elements/src/index.js b/packages/babel-plugin-transform-react-inline-elements/src/index.js index 5f394fc3f8b8..cb0e5a12c11e 100644 --- a/packages/babel-plugin-transform-react-inline-elements/src/index.js +++ b/packages/babel-plugin-transform-react-inline-elements/src/index.js @@ -1,7 +1,7 @@ export default function ({ types: t }) { function hasRefOrSpread(attrs) { for (let i = 0; i < attrs.length; i++) { - let attr = attrs[i]; + const attr = attrs[i]; if (t.isJSXSpreadAttribute(attr)) return true; if (isJSXAttributeOfName(attr, "ref")) return true; } @@ -22,14 +22,14 @@ export default function ({ types: t }) { return { visitor: { JSXElement(path, file) { - let { node } = path; + const { node } = path; // filter - let open = node.openingElement; + const open = node.openingElement; if (hasRefOrSpread(open.attributes)) return; // init - let props = t.objectExpression([]); + const props = t.objectExpression([]); let key = null; let type = open.name; @@ -42,26 +42,26 @@ export default function ({ types: t }) { } // props - for (let attr of (open.attributes: Array)) { + for (const attr of (open.attributes: Array)) { if (isJSXAttributeOfName(attr, "key")) { key = getAttributeValue(attr); } else { - let name = attr.name.name; - let propertyKey = t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name); + const name = attr.name.name; + const propertyKey = t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name); pushProp(props.properties, propertyKey, getAttributeValue(attr)); } } - let args = [type, props]; + const args = [type, props]; if (key || node.children.length) { - let children = t.react.buildChildren(node); + const children = t.react.buildChildren(node); args.push( key || t.unaryExpression("void", t.numericLiteral(0), true), ...children ); } - let el = t.callExpression(file.addHelper("jsx"), args); + const el = t.callExpression(file.addHelper("jsx"), args); path.replaceWith(el); } } diff --git a/packages/babel-plugin-transform-react-jsx-self/src/index.js b/packages/babel-plugin-transform-react-jsx-self/src/index.js index 2fd02a77ed05..39f223df6435 100644 --- a/packages/babel-plugin-transform-react-jsx-self/src/index.js +++ b/packages/babel-plugin-transform-react-jsx-self/src/index.js @@ -15,7 +15,7 @@ const TRACE_ID = "__self"; export default function ({ types: t }) { - let visitor = { + const visitor = { JSXOpeningElement({ node }) { const id = t.jSXIdentifier(TRACE_ID); const trace = t.thisExpression(); diff --git a/packages/babel-plugin-transform-react-jsx-source/src/index.js b/packages/babel-plugin-transform-react-jsx-source/src/index.js index cd296af979a0..039e9e5adc60 100644 --- a/packages/babel-plugin-transform-react-jsx-source/src/index.js +++ b/packages/babel-plugin-transform-react-jsx-source/src/index.js @@ -26,7 +26,7 @@ export default function ({ types: t }) { return t.objectExpression([fileNameProperty, lineNumberProperty]); } - let visitor = { + const visitor = { JSXOpeningElement(path, state) { const id = t.jSXIdentifier(TRACE_ID); const location = path.container.openingElement.loc; diff --git a/packages/babel-plugin-transform-react-jsx/src/index.js b/packages/babel-plugin-transform-react-jsx/src/index.js index 0a80ffac4bfa..12e127c90929 100644 --- a/packages/babel-plugin-transform-react-jsx/src/index.js +++ b/packages/babel-plugin-transform-react-jsx/src/index.js @@ -1,12 +1,12 @@ /* eslint max-len: 0 */ export default function ({ types: t }) { - let JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/; + const JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/; - let visitor = require("babel-helper-builder-react-jsx")({ + const visitor = require("babel-helper-builder-react-jsx")({ pre(state) { - let tagName = state.tagName; - let args = state.args; + const tagName = state.tagName; + const args = state.args; if (t.react.isCompatTag(tagName)) { args.push(t.stringLiteral(tagName)); } else { @@ -20,11 +20,11 @@ export default function ({ types: t }) { }); visitor.Program = function (path, state) { - let { file } = state; + const { file } = state; let id = state.opts.pragma || "React.createElement"; - for (let comment of (file.ast.comments: Array)) { - let matches = JSX_ANNOTATION_REGEX.exec(comment.value); + for (const comment of (file.ast.comments: Array)) { + const matches = JSX_ANNOTATION_REGEX.exec(comment.value); if (matches) { id = matches[1]; if (id === "React.DOM") { diff --git a/packages/babel-plugin-transform-runtime/src/index.js b/packages/babel-plugin-transform-runtime/src/index.js index 805df686ae10..8299547e911e 100644 --- a/packages/babel-plugin-transform-runtime/src/index.js +++ b/packages/babel-plugin-transform-runtime/src/index.js @@ -9,7 +9,7 @@ export default function ({ types: t }) { return Object.prototype.hasOwnProperty.call(obj, key); } - let HELPER_BLACKLIST = ["interopRequireWildcard", "interopRequireDefault"]; + const HELPER_BLACKLIST = ["interopRequireWildcard", "interopRequireDefault"]; return { pre(file) { @@ -30,7 +30,7 @@ export default function ({ types: t }) { visitor: { ReferencedIdentifier(path, state) { - let { node, parent, scope } = path; + const { node, parent, scope } = path; if (node.name === "regeneratorRuntime" && state.opts.regenerator !== false) { path.replaceWith(state.get("regeneratorIdentifier")); @@ -59,7 +59,7 @@ export default function ({ types: t }) { // we can't compile this if (path.node.arguments.length) return; - let callee = path.node.callee; + const callee = path.node.callee; if (!t.isMemberExpression(callee)) return; if (!callee.computed) return; if (!path.get("callee.property").matchesPattern("Symbol.iterator")) return; @@ -99,15 +99,15 @@ export default function ({ types: t }) { if (state.opts.polyfill === false) return; if (!path.isReferenced()) return; - let { node } = path; - let obj = node.object; - let prop = node.property; + const { node } = path; + const obj = node.object; + const prop = node.property; if (!t.isReferenced(obj, node)) return; if (node.computed) return; if (!has(definitions.methods, obj.name)) return; - let methods = definitions.methods[obj.name]; + const methods = definitions.methods[obj.name]; if (!has(methods, prop.name)) return; // doesn't reference the global @@ -115,7 +115,7 @@ export default function ({ types: t }) { // special case Object.defineProperty to not use core-js when using string keys if (obj.name === "Object" && prop.name === "defineProperty" && path.parentPath.isCallExpression()) { - let call = path.parentPath.node; + const call = path.parentPath.node; if (call.arguments.length === 3 && t.isLiteral(call.arguments[1])) return; } @@ -131,8 +131,8 @@ export default function ({ types: t }) { if (state.opts.polyfill === false) return; if (!path.isReferenced()) return; - let { node } = path; - let obj = node.object; + const { node } = path; + const obj = node.object; if (!has(definitions.builtins, obj.name)) return; if (path.scope.getBindingIdentifier(obj.name)) return; diff --git a/packages/babel-plugin-transform-strict-mode/src/index.js b/packages/babel-plugin-transform-strict-mode/src/index.js index 8ed2d181fb4f..fbd1dd913710 100644 --- a/packages/babel-plugin-transform-strict-mode/src/index.js +++ b/packages/babel-plugin-transform-strict-mode/src/index.js @@ -6,9 +6,9 @@ export default function () { Program(path, state) { if (state.opts.strict === false || state.opts.strictMode === false) return; - let { node } = path; + const { node } = path; - for (let directive of (node.directives: Array)) { + for (const directive of (node.directives: Array)) { if (directive.value.value === "use strict") return; } diff --git a/packages/babel-plugin-undeclared-variables-check/src/index.js b/packages/babel-plugin-undeclared-variables-check/src/index.js index a6400dd8c7af..9c63b00aaba6 100644 --- a/packages/babel-plugin-undeclared-variables-check/src/index.js +++ b/packages/babel-plugin-undeclared-variables-check/src/index.js @@ -4,9 +4,9 @@ export default function ({ messages }) { return { visitor: { ReferencedIdentifier(path) { - let { node, scope } = path; + const { node, scope } = path; - let binding = scope.getBinding(node.name); + const binding = scope.getBinding(node.name); if (binding && binding.kind === "type" && !path.parentPath.isFlow()) { throw path.buildCodeFrameError(messages.get("undeclaredVariableType", node.name), ReferenceError); } @@ -16,13 +16,13 @@ export default function ({ messages }) { // get the closest declaration to offer as a suggestion // the variable name may have just been mistyped - let bindings = scope.getAllBindings(); + const bindings = scope.getAllBindings(); let closest; let shortest = -1; - for (let name in bindings) { - let distance = leven(node.name, name); + for (const name in bindings) { + const distance = leven(node.name, name); if (distance <= 0 || distance > 3) continue; if (distance <= shortest) continue; diff --git a/packages/babel-polyfill/src/index.js b/packages/babel-polyfill/src/index.js index 0cb9b282d619..2dfde7b6d754 100644 --- a/packages/babel-polyfill/src/index.js +++ b/packages/babel-polyfill/src/index.js @@ -12,7 +12,7 @@ import "regenerator-runtime/runtime"; import "core-js/fn/regexp/escape"; -let DEFINE_PROPERTY = "defineProperty"; +const DEFINE_PROPERTY = "defineProperty"; function define(O, key, value) { O[key] || Object[DEFINE_PROPERTY](O, key, { writable: true, diff --git a/packages/babel-preset-es2015/test/index.js b/packages/babel-preset-es2015/test/index.js index 7653dbb6f97e..8047319eb6b3 100644 --- a/packages/babel-preset-es2015/test/index.js +++ b/packages/babel-preset-es2015/test/index.js @@ -1,5 +1,5 @@ -let es2015 = require("../lib"); -let expect = require("chai").expect; +const es2015 = require("../lib"); +const expect = require("chai").expect; describe("es2015 preset", function () { it("exposes an object", function () { diff --git a/packages/babel-preset-es2015/test/traceur.js b/packages/babel-preset-es2015/test/traceur.js index a4bfd87c3f1a..da8c33beaeef 100644 --- a/packages/babel-preset-es2015/test/traceur.js +++ b/packages/babel-preset-es2015/test/traceur.js @@ -1,4 +1,4 @@ -let _ = require("lodash"); +const _ = require("lodash"); require("babel-helper-transform-fixture-test-runner")(__dirname + "/fixtures/traceur", "traceur", { ignoreSuites: [ diff --git a/packages/babel-register/src/node.js b/packages/babel-register/src/node.js index 91edc8c65be8..19e052f5007a 100644 --- a/packages/babel-register/src/node.js +++ b/packages/babel-register/src/node.js @@ -12,7 +12,7 @@ sourceMapSupport.install({ handleUncaughtExceptions: false, environment : "node", retrieveSourceMap(source) { - let map = maps && maps[source]; + const map = maps && maps[source]; if (map) { return { url: null, @@ -27,15 +27,15 @@ sourceMapSupport.install({ registerCache.load(); let cache = registerCache.get(); -let transformOpts = {}; +const transformOpts = {}; let ignore; let only; let oldHandlers = {}; -let maps = {}; +const maps = {}; -let cwd = process.cwd(); +const cwd = process.cwd(); function getRelativePath(filename) { return path.relative(cwd, filename); @@ -49,7 +49,7 @@ function compile(filename) { let result; // merge in base options and resolve all the plugins and presets relative to this file - let opts = new OptionManager().init(extend( + const opts = new OptionManager().init(extend( { sourceRoot: path.dirname(filename) }, // sourceRoot can be overwritten deepClone(transformOpts), { filename } @@ -57,11 +57,11 @@ function compile(filename) { let cacheKey = `${JSON.stringify(opts)}:${babel.version}`; - let env = process.env.BABEL_ENV || process.env.NODE_ENV; + const env = process.env.BABEL_ENV || process.env.NODE_ENV; if (env) cacheKey += `:${env}`; if (cache) { - let cached = cache[cacheKey]; + const cached = cache[cacheKey]; if (cached && cached.mtime === mtime(filename)) { result = cached; } @@ -100,7 +100,7 @@ function loader(m, filename) { } function registerExtension(ext) { - let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"]; + const old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"]; require.extensions[ext] = function (m, filename) { if (shouldIgnore(filename)) { diff --git a/packages/babel-template/src/index.js b/packages/babel-template/src/index.js index 5413e5d6ab90..4abd2a460803 100644 --- a/packages/babel-template/src/index.js +++ b/packages/babel-template/src/index.js @@ -7,8 +7,8 @@ import traverse from "babel-traverse"; import * as babylon from "babylon"; import * as t from "babel-types"; -let FROM_TEMPLATE = "_fromTemplate"; //Symbol(); // todo: probably wont get copied over -let TEMPLATE_SKIP = Symbol(); +const FROM_TEMPLATE = "_fromTemplate"; //Symbol(); // todo: probably wont get copied over +const TEMPLATE_SKIP = Symbol(); export default function (code: string, opts?: Object): Function { // since we lazy parse the template, we get the current stack so we have the @@ -60,7 +60,7 @@ export default function (code: string, opts?: Object): Function { function useTemplate(ast, nodes?: Array) { ast = cloneDeep(ast); - let { program } = ast; + const { program } = ast; if (nodes.length) { traverse(ast, templateVisitor, null, nodes); @@ -73,7 +73,7 @@ function useTemplate(ast, nodes?: Array) { } } -let templateVisitor = { +const templateVisitor = { // 360 noScope: true, @@ -91,7 +91,7 @@ let templateVisitor = { if (has(args[0], node.name)) { replacement = args[0][node.name]; } else if (node.name[0] === "$") { - let i = +node.name.slice(1); + const i = +node.name.slice(1); if (args[i]) replacement = args[i]; } } diff --git a/packages/babel-template/test/index.js b/packages/babel-template/test/index.js index f64090e4a839..6e4ae78544c0 100644 --- a/packages/babel-template/test/index.js +++ b/packages/babel-template/test/index.js @@ -1,8 +1,8 @@ -let generator = require("../../babel-generator").default; -let template = require("../lib"); -let chai = require("chai"); +const generator = require("../../babel-generator").default; +const template = require("../lib"); +const chai = require("chai"); -let comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; +const comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; describe("templating", function () { it("import statement will cause parser to throw by default", function () { @@ -18,13 +18,13 @@ describe("templating", function () { }); it("should strip comments by default", function () { - let code = "const add = (a, b) => a + b;"; - let output = template(comments)(); + const code = "const add = (a, b) => a + b;"; + const output = template(comments)(); chai.expect(generator(output).code).to.be.equal(code); }); it("should preserve comments with a flag", function () { - let output = template(comments, {preserveComments: true})(); + const output = template(comments, {preserveComments: true})(); chai.expect(generator(output).code).to.be.equal(comments); }); }); diff --git a/packages/babel-traverse/src/context.js b/packages/babel-traverse/src/context.js index b73ff3f7bfb1..3be2d90f85d5 100644 --- a/packages/babel-traverse/src/context.js +++ b/packages/babel-traverse/src/context.js @@ -1,7 +1,7 @@ import NodePath from "./path"; import * as t from "babel-types"; -let testing = process.env.NODE_ENV === "test"; +const testing = process.env.NODE_ENV === "test"; export default class TraversalContext { constructor(scope, opts, state, parentPath) { @@ -23,18 +23,18 @@ export default class TraversalContext { */ shouldVisit(node): boolean { - let opts = this.opts; + const opts = this.opts; if (opts.enter || opts.exit) return true; // check if we have a visitor for this node if (opts[node.type]) return true; // check if we're going to traverse into this node - let keys: ?Array = t.VISITOR_KEYS[node.type]; + const keys: ?Array = t.VISITOR_KEYS[node.type]; if (!keys || !keys.length) return false; // we need to traverse into this node so ensure that it has children to traverse into! - for (let key of keys) { + for (const key of keys) { if (node[key]) return true; } @@ -69,11 +69,11 @@ export default class TraversalContext { // nothing to traverse! if (container.length === 0) return false; - let queue = []; + const queue = []; // build up initial queue for (let key = 0; key < container.length; key++) { - let node = container[key]; + const node = container[key]; if (node && this.shouldVisit(node)) { queue.push(this.create(parent, container, key, listKey)); } @@ -97,11 +97,11 @@ export default class TraversalContext { this.queue = queue; this.priorityQueue = []; - let visited = []; + const visited = []; let stop = false; // visit the queue - for (let path of queue) { + for (const path of queue) { path.resync(); if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { @@ -136,7 +136,7 @@ export default class TraversalContext { } // clear queue - for (let path of queue) { + for (const path of queue) { path.popContext(); } @@ -147,7 +147,7 @@ export default class TraversalContext { } visit(node, key) { - let nodes = node[key]; + const nodes = node[key]; if (!nodes) return false; if (Array.isArray(nodes)) { diff --git a/packages/babel-traverse/src/index.js b/packages/babel-traverse/src/index.js index 6a3d4660a4b7..464a5a150fab 100644 --- a/packages/babel-traverse/src/index.js +++ b/packages/babel-traverse/src/index.js @@ -46,11 +46,11 @@ traverse.cheap = function (node, enter) { }; traverse.node = function (node: Object, opts: Object, scope: Object, state: Object, parentPath: Object, skipKeys?) { - let keys: Array = t.VISITOR_KEYS[node.type]; + const keys: Array = t.VISITOR_KEYS[node.type]; if (!keys) return; - let context = new TraversalContext(scope, opts, state, parentPath); - for (let key of keys) { + const context = new TraversalContext(scope, opts, state, parentPath); + for (const key of keys) { if (skipKeys && skipKeys[key]) continue; if (context.visit(node, key)) return; } @@ -81,7 +81,7 @@ traverse.hasType = function (tree: Object, scope: Object, type: Object, blacklis // the type we're looking for is the same as the passed node if (tree.type === type) return true; - let state = { + const state = { has: false, type: type }; diff --git a/packages/babel-traverse/src/path/ancestry.js b/packages/babel-traverse/src/path/ancestry.js index 35fb7b34359c..245910aa6a98 100644 --- a/packages/babel-traverse/src/path/ancestry.js +++ b/packages/babel-traverse/src/path/ancestry.js @@ -60,10 +60,10 @@ export function getStatementParent() { export function getEarliestCommonAncestorFrom(paths: Array): NodePath { return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { let earliest; - let keys = t.VISITOR_KEYS[deepest.type]; + const keys = t.VISITOR_KEYS[deepest.type]; - for (let ancestry of (ancestries: Array)) { - let path = ancestry[i + 1]; + for (const ancestry of (ancestries: Array)) { + const path = ancestry[i + 1]; // first path if (!earliest) { @@ -81,8 +81,8 @@ export function getEarliestCommonAncestorFrom(paths: Array): NodePath } // handle keys - let earliestKeyIndex = keys.indexOf(earliest.parentKey); - let currentKeyIndex = keys.indexOf(path.parentKey); + const earliestKeyIndex = keys.indexOf(earliest.parentKey); + const currentKeyIndex = keys.indexOf(path.parentKey); if (earliestKeyIndex > currentKeyIndex) { // key appears before so it's earlier earliest = path; @@ -115,8 +115,8 @@ export function getDeepestCommonAncestorFrom(paths: Array, filter?: Fu let lastCommonIndex, lastCommon; // get the ancestors of the path, breaking when the parent exceeds ourselves - let ancestries = paths.map((path) => { - let ancestry = []; + const ancestries = paths.map((path) => { + const ancestry = []; do { ancestry.unshift(path); @@ -131,13 +131,13 @@ export function getDeepestCommonAncestorFrom(paths: Array, filter?: Fu }); // get the first ancestry so we have a seed to assess all other ancestries with - let first = ancestries[0]; + const first = ancestries[0]; // check ancestor equality depthLoop: for (let i = 0; i < minDepth; i++) { - let shouldMatch = first[i]; + const shouldMatch = first[i]; - for (let ancestry of (ancestries: Array)) { + for (const ancestry of (ancestries: Array)) { if (ancestry[i] !== shouldMatch) { // we've hit a snag break depthLoop; @@ -168,7 +168,7 @@ export function getDeepestCommonAncestorFrom(paths: Array, filter?: Fu export function getAncestry() { let path = this; - let paths = []; + const paths = []; do { paths.push(path); } while (path = path.parentPath); @@ -192,7 +192,7 @@ export function isDescendant(maybeAncestor) { export function inType() { let path = this; while (path) { - for (let type of (arguments: Array)) { + for (const type of (arguments: Array)) { if (path.node.type === type) return true; } path = path.parentPath; @@ -235,11 +235,11 @@ export function inType() { */ export function inShadow(key?) { - let parentFn = this.isFunction() ? this : this.findParent((p) => p.isFunction()); + const parentFn = this.isFunction() ? this : this.findParent((p) => p.isFunction()); if (!parentFn) return; if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { - let shadow = parentFn.node.shadow; + const shadow = parentFn.node.shadow; // this is because sometimes we may have a `shadow` value of: // diff --git a/packages/babel-traverse/src/path/comments.js b/packages/babel-traverse/src/path/comments.js index b7f0ae1a07a6..8aec4d5fa5e6 100644 --- a/packages/babel-traverse/src/path/comments.js +++ b/packages/babel-traverse/src/path/comments.js @@ -8,11 +8,11 @@ export function shareCommentsWithSiblings() { // NOTE: this assumes numbered keys if (typeof this.key === "string") return; - let node = this.node; + const node = this.node; if (!node) return; - let trailing = node.trailingComments; - let leading = node.leadingComments; + const trailing = node.trailingComments; + const leading = node.leadingComments; if (!trailing && !leading) return; let prev = this.getSibling(this.key - 1); @@ -39,10 +39,10 @@ export function addComment(type, content, line?) { export function addComments(type: string, comments: Array) { if (!comments) return; - let node = this.node; + const node = this.node; if (!node) return; - let key = `${type}Comments`; + const key = `${type}Comments`; if (node[key]) { node[key] = node[key].concat(comments); diff --git a/packages/babel-traverse/src/path/context.js b/packages/babel-traverse/src/path/context.js index 6710171c578e..c74cb356ddbd 100644 --- a/packages/babel-traverse/src/path/context.js +++ b/packages/babel-traverse/src/path/context.js @@ -3,7 +3,7 @@ import traverse from "../index"; export function call(key): boolean { - let opts = this.opts; + const opts = this.opts; this.debug(() => key); @@ -21,13 +21,13 @@ export function call(key): boolean { export function _call(fns?: Array): boolean { if (!fns) return false; - for (let fn of fns) { + for (const fn of fns) { if (!fn) continue; - let node = this.node; + const node = this.node; if (!node) return true; - let ret = fn.call(this.state, this, this.state); + const ret = fn.call(this.state, this, this.state); if (ret) throw new Error(`Unexpected return value from visitor method ${fn}`); // node has been replaced, it will have been requeued @@ -40,7 +40,7 @@ export function _call(fns?: Array): boolean { } export function isBlacklisted(): boolean { - let blacklist = this.opts.blacklist; + const blacklist = this.opts.blacklist; return blacklist && blacklist.indexOf(this.node.type) > -1; } @@ -155,7 +155,7 @@ export function _resyncKey() { } } } else { - for (let key in this.container) { + for (const key in this.container) { if (this.container[key] === this.node) { return this.setKey(key); } @@ -169,7 +169,7 @@ export function _resyncKey() { export function _resyncList() { if (!this.parent || !this.inList) return; - let newContainer = this.parent[this.listKey]; + const newContainer = this.parent[this.listKey]; if (this.container === newContainer) return; // container is out of sync. this is likely the result of it being reassigned @@ -214,9 +214,9 @@ export function requeue(pathToQueue = this) { // TODO(loganfsmyth): This should be switched back to queue in parent contexts // automatically once #2892 and #4135 have been resolved. See #4140. // let contexts = this._getQueueContexts(); - let contexts = this.contexts; + const contexts = this.contexts; - for (let context of contexts) { + for (const context of contexts) { context.maybeQueue(pathToQueue); } } diff --git a/packages/babel-traverse/src/path/conversion.js b/packages/babel-traverse/src/path/conversion.js index 27079529d71c..a9ff22fc640f 100644 --- a/packages/babel-traverse/src/path/conversion.js +++ b/packages/babel-traverse/src/path/conversion.js @@ -3,7 +3,7 @@ import * as t from "babel-types"; export function toComputedKey(): Object { - let node = this.node; + const node = this.node; let key; if (this.isMemberExpression()) { @@ -31,7 +31,7 @@ export function arrowFunctionToShadowed() { this.ensureBlock(); - let { node } = this; + const { node } = this; node.expression = false; node.type = "FunctionExpression"; node.shadow = node.shadow || true; diff --git a/packages/babel-traverse/src/path/evaluation.js b/packages/babel-traverse/src/path/evaluation.js index 3b41b188c6ce..82c15a743ef7 100644 --- a/packages/babel-traverse/src/path/evaluation.js +++ b/packages/babel-traverse/src/path/evaluation.js @@ -29,7 +29,7 @@ const INVALID_METHODS = ["random"]; */ export function evaluateTruthy(): boolean { - let res = this.evaluate(); + const res = this.evaluate(); if (res.confident) return !!res.value; } @@ -51,7 +51,7 @@ export function evaluateTruthy(): boolean { export function evaluate(): { confident: boolean; value: any } { let confident = true; let deoptPath: ?NodePath; - let seen = new Map; + const seen = new Map; function deopt(path) { if (!confident) return; @@ -75,10 +75,10 @@ export function evaluate(): { confident: boolean; value: any } { // a = g * this.foo // function evaluate(path) { - let { node } = path; + const { node } = path; if (seen.has(node)) { - let existing = seen.get(node); + const existing = seen.get(node); if (existing.resolved) { return existing.value; } else { @@ -86,10 +86,10 @@ export function evaluate(): { confident: boolean; value: any } { return; } } else { - let item = { resolved: false }; + const item = { resolved: false }; seen.set(node, item); - let val = _evaluate(path); + const val = _evaluate(path); if (confident) { item.resolved = true; item.value = val; @@ -101,10 +101,10 @@ export function evaluate(): { confident: boolean; value: any } { function _evaluate(path) { if (!confident) return; - let { node } = path; + const { node } = path; if (path.isSequenceExpression()) { - let exprs = path.get("expressions"); + const exprs = path.get("expressions"); return evaluate(exprs[exprs.length - 1]); } @@ -120,9 +120,9 @@ export function evaluate(): { confident: boolean; value: any } { let str = ""; let i = 0; - let exprs = path.get("expressions"); + const exprs = path.get("expressions"); - for (let elem of (node.quasis: Array)) { + for (const elem of (node.quasis: Array)) { // not confident, evaluated an expression we don't like if (!confident) break; @@ -130,7 +130,7 @@ export function evaluate(): { confident: boolean; value: any } { str += elem.value.cooked; // add on interpolated expression if it's present - let expr = exprs[i++]; + const expr = exprs[i++]; if (expr) str += String(evaluate(expr)); } @@ -139,7 +139,7 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isConditionalExpression()) { - let testResult = evaluate(path.get("test")); + const testResult = evaluate(path.get("test")); if (!confident) return; if (testResult) { return evaluate(path.get("consequent")); @@ -154,12 +154,12 @@ export function evaluate(): { confident: boolean; value: any } { // "foo".length if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { - let property = path.get("property"); - let object = path.get("object"); + const property = path.get("property"); + const object = path.get("object"); if (object.isLiteral() && property.isIdentifier()) { - let value = object.node.value; - let type = typeof value; + const value = object.node.value; + const type = typeof value; if (type === "number" || type === "string") { return value[property.node.name]; } @@ -167,7 +167,7 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isReferencedIdentifier()) { - let binding = path.scope.getBinding(node.name); + const binding = path.scope.getBinding(node.name); if (binding && binding.constantViolations.length > 0) { return deopt(binding.path); @@ -188,7 +188,7 @@ export function evaluate(): { confident: boolean; value: any } { return NaN; } - let resolved = path.resolve(); + const resolved = path.resolve(); if (resolved === path) { return deopt(path); } else { @@ -203,12 +203,12 @@ export function evaluate(): { confident: boolean; value: any } { return undefined; } - let argument = path.get("argument"); + const argument = path.get("argument"); if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { return "function"; } - let arg = evaluate(argument); + const arg = evaluate(argument); if (!confident) return; switch (node.operator) { case "!": return !arg; @@ -220,8 +220,8 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isArrayExpression()) { - let arr = []; - let elems: Array = path.get("elements"); + const arr = []; + const elems: Array = path.get("elements"); for (let elem of elems) { elem = elem.evaluate(); @@ -235,9 +235,9 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isObjectExpression()) { - let obj = {}; - let props: Array = path.get("properties"); - for (let prop of props) { + const obj = {}; + const props: Array = path.get("properties"); + for (const prop of props) { if (prop.isObjectMethod() || prop.isSpreadProperty()) { return deopt(prop); } @@ -268,12 +268,12 @@ export function evaluate(): { confident: boolean; value: any } { if (path.isLogicalExpression()) { // If we are confident that one side of an && is false, or the left // side of an || is true, we can be confident about the entire expression - let wasConfident = confident; - let left = evaluate(path.get("left")); - let leftConfident = confident; + const wasConfident = confident; + const left = evaluate(path.get("left")); + const leftConfident = confident; confident = wasConfident; - let right = evaluate(path.get("right")); - let rightConfident = confident; + const right = evaluate(path.get("right")); + const rightConfident = confident; confident = leftConfident && rightConfident; switch (node.operator) { @@ -300,9 +300,9 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isBinaryExpression()) { - let left = evaluate(path.get("left")); + const left = evaluate(path.get("left")); if (!confident) return; - let right = evaluate(path.get("right")); + const right = evaluate(path.get("right")); if (!confident) return; switch (node.operator) { @@ -330,7 +330,7 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isCallExpression()) { - let callee = path.get("callee"); + const callee = path.get("callee"); let context; let func; @@ -340,8 +340,8 @@ export function evaluate(): { confident: boolean; value: any } { } if (callee.isMemberExpression()) { - let object = callee.get("object"); - let property = callee.get("property"); + const object = callee.get("object"); + const property = callee.get("property"); // Math.min(1, 2) if (object.isIdentifier() && property.isIdentifier() && VALID_CALLEES.indexOf(object.node.name) >= 0 && INVALID_METHODS.indexOf(property.node.name) < 0) { @@ -351,7 +351,7 @@ export function evaluate(): { confident: boolean; value: any } { // "abc".charCodeAt(4) if (object.isLiteral() && property.isIdentifier()) { - let type = typeof object.node.value; + const type = typeof object.node.value; if (type === "string" || type === "number") { context = object.node.value; func = context[property.node.name]; @@ -360,7 +360,7 @@ export function evaluate(): { confident: boolean; value: any } { } if (func) { - let args = path.get("arguments").map(evaluate); + const args = path.get("arguments").map(evaluate); if (!confident) return; return func.apply(context, args); diff --git a/packages/babel-traverse/src/path/family.js b/packages/babel-traverse/src/path/family.js index f7a630d0a79c..d17ae8aed709 100644 --- a/packages/babel-traverse/src/path/family.js +++ b/packages/babel-traverse/src/path/family.js @@ -33,7 +33,7 @@ export function getOpposite() { export function getCompletionRecords(): Array { let paths = []; - let add = function (path) { + const add = function (path) { if (path) paths = paths.concat(path.getCompletionRecords()); }; @@ -69,7 +69,7 @@ export function getSibling(key) { export function get(key: string, context?: boolean | TraversalContext): NodePath { if (context === true) context = this.context; - let parts = key.split("."); + const parts = key.split("."); if (parts.length === 1) { // "foo" return this._getKey(key, context); } else { // "foo.bar" @@ -78,8 +78,8 @@ export function get(key: string, context?: boolean | TraversalContext): NodePath } export function _getKey(key, context?) { - let node = this.node; - let container = node[key]; + const node = this.node; + const container = node[key]; if (Array.isArray(container)) { // requested a container so give them all the paths @@ -104,7 +104,7 @@ export function _getKey(key, context?) { export function _getPattern(parts, context) { let path = this; - for (let part of (parts: Array)) { + for (const part of (parts: Array)) { if (part === ".") { path = path.parentPath; } else { @@ -130,20 +130,20 @@ export function getOuterBindingIdentifiers(duplicates?) { // path.getBindingIdentifiers returns nodes where the following re-implementation // returns paths export function getBindingIdentifierPaths(duplicates = false, outerOnly = false) { - let path = this; + const path = this; let search = [].concat(path); - let ids = Object.create(null); + const ids = Object.create(null); while (search.length) { - let id = search.shift(); + const id = search.shift(); if (!id) continue; if (!id.node) continue; - let keys = t.getBindingIdentifiers.keys[id.node.type]; + const keys = t.getBindingIdentifiers.keys[id.node.type]; if (id.isIdentifier()) { if (duplicates) { - let _ids = ids[id.node.name] = ids[id.node.name] || []; + const _ids = ids[id.node.name] = ids[id.node.name] || []; _ids.push(id); } else { ids[id.node.name] = id; @@ -171,8 +171,8 @@ export function getBindingIdentifierPaths(duplicates = false, outerOnly = false) if (keys) { for (let i = 0; i < keys.length; i++) { - let key = keys[i]; - let child = id.get(key); + const key = keys[i]; + const child = id.get(key); if (Array.isArray(child) || child.node) { search = search.concat(child); } diff --git a/packages/babel-traverse/src/path/index.js b/packages/babel-traverse/src/path/index.js index 1b5b58919018..853a735bb8bb 100644 --- a/packages/babel-traverse/src/path/index.js +++ b/packages/babel-traverse/src/path/index.js @@ -11,7 +11,7 @@ import Scope from "../scope"; import * as t from "babel-types"; import { path as pathCache } from "../cache"; -let debug = buildDebug("babel"); +const debug = buildDebug("babel"); export default class NodePath { constructor(hub: Hub, parent: Object) { @@ -67,9 +67,9 @@ export default class NodePath { invariant(parent, "To get a node path the parent needs to exist"); - let targetNode = container[key]; + const targetNode = container[key]; - let paths = pathCache.get(parent) || []; + const paths = pathCache.get(parent) || []; if (!pathCache.has(parent)) { pathCache.set(parent, paths); } @@ -77,7 +77,7 @@ export default class NodePath { let path; for (let i = 0; i < paths.length; i++) { - let pathCheck = paths[i]; + const pathCheck = paths[i]; if (pathCheck.node === targetNode) { path = pathCheck; break; @@ -137,7 +137,7 @@ export default class NodePath { } getPathLocation(): string { - let parts = []; + const parts = []; let path = this; do { let key = path.key; @@ -165,8 +165,8 @@ assign(NodePath.prototype, require("./modification")); assign(NodePath.prototype, require("./family")); assign(NodePath.prototype, require("./comments")); -for (let type of (t.TYPES: Array)) { - let typeKey = `is${type}`; +for (const type of (t.TYPES: Array)) { + const typeKey = `is${type}`; NodePath.prototype[typeKey] = function (opts) { return t[typeKey](this.node, opts); }; @@ -178,11 +178,11 @@ for (let type of (t.TYPES: Array)) { }; } -for (let type in virtualTypes) { +for (const type in virtualTypes) { if (type[0] === "_") continue; if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); - let virtualType = virtualTypes[type]; + const virtualType = virtualTypes[type]; NodePath.prototype[`is${type}`] = function (opts) { return virtualType.checkPath(this, opts); diff --git a/packages/babel-traverse/src/path/inference/index.js b/packages/babel-traverse/src/path/inference/index.js index 55a52911a655..976d327082b9 100644 --- a/packages/babel-traverse/src/path/inference/index.js +++ b/packages/babel-traverse/src/path/inference/index.js @@ -19,13 +19,13 @@ export function getTypeAnnotation(): Object { */ export function _getTypeAnnotation(): ?Object { - let node = this.node; + const node = this.node; if (!node) { // handle initializerless variables, add in checks for loop initializers too if (this.key === "init" && this.parentPath.isVariableDeclarator()) { - let declar = this.parentPath.parentPath; - let declarParent = declar.parentPath; + const declar = this.parentPath.parentPath; + const declarParent = declar.parentPath; // for (let NODE in bar) {} if (declar.key === "left" && declarParent.isForInStatement()) { @@ -87,11 +87,11 @@ function _isBaseType(baseName: string, type?, soft?): boolean { } export function couldBeBaseType(name: string): boolean { - let type = this.getTypeAnnotation(); + const type = this.getTypeAnnotation(); if (t.isAnyTypeAnnotation(type)) return true; if (t.isUnionTypeAnnotation(type)) { - for (let type2 of (type.types: Array)) { + for (const type2 of (type.types: Array)) { if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { return true; } @@ -103,7 +103,7 @@ export function couldBeBaseType(name: string): boolean { } export function baseTypeStrictlyMatches(right: NodePath) { - let left = this.getTypeAnnotation(); + const left = this.getTypeAnnotation(); right = right.getTypeAnnotation(); if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { @@ -112,6 +112,6 @@ export function baseTypeStrictlyMatches(right: NodePath) { } export function isGenericType(genericName: string): boolean { - let type = this.getTypeAnnotation(); + const type = this.getTypeAnnotation(); return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); } diff --git a/packages/babel-traverse/src/path/inference/inferer-reference.js b/packages/babel-traverse/src/path/inference/inferer-reference.js index 4b1d8e58a926..16effb09430d 100644 --- a/packages/babel-traverse/src/path/inference/inferer-reference.js +++ b/packages/babel-traverse/src/path/inference/inferer-reference.js @@ -6,7 +6,7 @@ export default function (node: Object) { // check if a binding exists of this value and if so then return a union type of all // possible types that the binding could be - let binding = this.scope.getBinding(node.name); + const binding = this.scope.getBinding(node.name); if (binding) { if (binding.identifier.typeAnnotation) { return binding.identifier.typeAnnotation; @@ -26,17 +26,17 @@ export default function (node: Object) { } function getTypeAnnotationBindingConstantViolations(path, name) { - let binding = path.scope.getBinding(name); + const binding = path.scope.getBinding(name); - let types = []; + const types = []; path.typeAnnotation = t.unionTypeAnnotation(types); - let functionConstantViolations = []; + const functionConstantViolations = []; let constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); - let testType = getConditionalAnnotation(path, name); + const testType = getConditionalAnnotation(path, name); if (testType) { - let testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); + const testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); // remove constant violations observed before the IfStatement constantViolations = constantViolations.filter((path) => testConstantViolations.indexOf(path) < 0); @@ -76,7 +76,7 @@ function getTypeAnnotationBindingConstantViolations(path, name) { constantViolations = constantViolations.concat(functionConstantViolations); // push on inferred types of violated paths - for (let violation of (constantViolations: Array)) { + for (const violation of (constantViolations: Array)) { types.push(violation.getTypeAnnotation()); } } @@ -87,21 +87,21 @@ function getTypeAnnotationBindingConstantViolations(path, name) { } function getConstantViolationsBefore(binding, path, functions) { - let violations = binding.constantViolations.slice(); + const violations = binding.constantViolations.slice(); violations.unshift(binding.path); return violations.filter((violation) => { violation = violation.resolve(); - let status = violation._guessExecutionStatusRelativeTo(path); + const status = violation._guessExecutionStatusRelativeTo(path); if (functions && status === "function") functions.push(violation); return status === "before"; }); } function inferAnnotationFromBinaryExpression(name, path) { - let operator = path.node.operator; + const operator = path.node.operator; - let right = path.get("right").resolve(); - let left = path.get("left").resolve(); + const right = path.get("right").resolve(); + const left = path.get("left").resolve(); let target; if (left.isIdentifier({ name })) { @@ -138,7 +138,7 @@ function inferAnnotationFromBinaryExpression(name, path) { if (!typePath.isLiteral()) return; // and that it's a string so we can infer it - let typeValue = typePath.node.value; + const typeValue = typePath.node.value; if (typeof typeValue !== "string") return; // and that the argument of the typeof path references us! @@ -164,15 +164,15 @@ function getParentConditionalPath(path) { } function getConditionalAnnotation(path, name) { - let ifStatement = getParentConditionalPath(path); + const ifStatement = getParentConditionalPath(path); if (!ifStatement) return; - let test = ifStatement.get("test"); - let paths = [test]; - let types = []; + const test = ifStatement.get("test"); + const paths = [test]; + const types = []; do { - let path = paths.shift().resolve(); + const path = paths.shift().resolve(); if (path.isLogicalExpression()) { paths.push(path.get("left")); @@ -180,7 +180,7 @@ function getConditionalAnnotation(path, name) { } if (path.isBinaryExpression()) { - let type = inferAnnotationFromBinaryExpression(name, path); + const type = inferAnnotationFromBinaryExpression(name, path); if (type) types.push(type); } } while (paths.length); diff --git a/packages/babel-traverse/src/path/inference/inferers.js b/packages/babel-traverse/src/path/inference/inferers.js index ec372f6825d7..be90de0cc0f8 100644 --- a/packages/babel-traverse/src/path/inference/inferers.js +++ b/packages/babel-traverse/src/path/inference/inferers.js @@ -3,7 +3,7 @@ import * as t from "babel-types"; export { default as Identifier } from "./inferer-reference"; export function VariableDeclarator() { - let id = this.get("id"); + const id = this.get("id"); if (id.isIdentifier()) { return this.get("init").getTypeAnnotation(); @@ -30,7 +30,7 @@ export function TemplateLiteral() { } export function UnaryExpression(node) { - let operator = node.operator; + const operator = node.operator; if (operator === "void") { return t.voidTypeAnnotation(); @@ -44,15 +44,15 @@ export function UnaryExpression(node) { } export function BinaryExpression(node) { - let operator = node.operator; + const operator = node.operator; if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { return t.numberTypeAnnotation(); } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { return t.booleanTypeAnnotation(); } else if (operator === "+") { - let right = this.get("right"); - let left = this.get("left"); + const right = this.get("right"); + const left = this.get("left"); if (left.isBaseType("number") && right.isBaseType("number")) { // both numbers so this will be a number @@ -93,7 +93,7 @@ export function AssignmentExpression() { } export function UpdateExpression(node) { - let operator = node.operator; + const operator = node.operator; if (operator === "++" || operator === "--") { return t.numberTypeAnnotation(); } diff --git a/packages/babel-traverse/src/path/introspection.js b/packages/babel-traverse/src/path/introspection.js index be7a2755c537..e8e54f18c01f 100644 --- a/packages/babel-traverse/src/path/introspection.js +++ b/packages/babel-traverse/src/path/introspection.js @@ -15,17 +15,17 @@ export function matchesPattern(pattern: string, allowPartial?: boolean): boolean // not a member expression if (!this.isMemberExpression()) return false; - let parts = pattern.split("."); - let search = [this.node]; + const parts = pattern.split("."); + const search = [this.node]; let i = 0; function matches(name) { - let part = parts[i]; + const part = parts[i]; return part === "*" || name === part; } while (search.length) { - let node = search.shift(); + const node = search.shift(); if (allowPartial && i === parts.length) { return true; @@ -68,7 +68,7 @@ export function matchesPattern(pattern: string, allowPartial?: boolean): boolean */ export function has(key): boolean { - let val = this.node && this.node[key]; + const val = this.node && this.node[key]; if (val && Array.isArray(val)) { return !!val.length; } else { @@ -88,7 +88,7 @@ export function isStatic() { * Alias of `has`. */ -export let is = has; +export const is = has; /** * Opposite of `has`. @@ -160,7 +160,7 @@ export function isCompletionRecord(allowInsideFunction?) { let first = true; do { - let container = path.container; + const container = path.container; // we're in a function so can't be a completion record if (path.isFunction() && !first) { @@ -199,11 +199,11 @@ export function isStatementOrBlock() { export function referencesImport(moduleSource, importName) { if (!this.isReferencedIdentifier()) return false; - let binding = this.scope.getBinding(this.node.name); + const binding = this.scope.getBinding(this.node.name); if (!binding || binding.kind !== "module") return false; - let path = binding.path; - let parent = path.parentPath; + const path = binding.path; + const parent = path.parentPath; if (!parent.isImportDeclaration()) return false; // check moduleSource @@ -233,7 +233,7 @@ export function referencesImport(moduleSource, importName) { */ export function getSource() { - let node = this.node; + const node = this.node; if (node.end) { return this.hub.file.code.slice(node.start, node.end); } else { @@ -254,13 +254,13 @@ export function willIMaybeExecuteBefore(target) { export function _guessExecutionStatusRelativeTo(target) { // check if the two paths are in different functions, we can't track execution of these - let targetFuncParent = target.scope.getFunctionParent(); - let selfFuncParent = this.scope.getFunctionParent(); + const targetFuncParent = target.scope.getFunctionParent(); + const selfFuncParent = this.scope.getFunctionParent(); // here we check the `node` equality as sometimes we may have different paths for the // same node due to path thrashing if (targetFuncParent.node !== selfFuncParent.node) { - let status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); + const status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); if (status) { return status; } else { @@ -268,17 +268,17 @@ export function _guessExecutionStatusRelativeTo(target) { } } - let targetPaths = target.getAncestry(); + const targetPaths = target.getAncestry(); if (targetPaths.indexOf(this) >= 0) return "after"; - let selfPaths = this.getAncestry(); + const selfPaths = this.getAncestry(); // get ancestor where the branches intersect let commonPath; let targetIndex; let selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { - let selfPath = selfPaths[selfIndex]; + const selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; @@ -290,8 +290,8 @@ export function _guessExecutionStatusRelativeTo(target) { } // get the relationship paths that associate these nodes to their common ancestor - let targetRelationship = targetPaths[targetIndex - 1]; - let selfRelationship = selfPaths[selfIndex - 1]; + const targetRelationship = targetPaths[targetIndex - 1]; + const selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } @@ -302,28 +302,28 @@ export function _guessExecutionStatusRelativeTo(target) { } // otherwise we're associated by a parent node, check which key comes before the other - let targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); - let selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); + const targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); + const selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; } export function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { - let targetFuncPath = targetFuncParent.path; + const targetFuncPath = targetFuncParent.path; if (!targetFuncPath.isFunctionDeclaration()) return; // so we're in a completely different function, if this is a function declaration // then we can be a bit smarter and handle cases where the function is either // a. not called at all (part of an export) // b. called directly - let binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); + const binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); // no references! if (!binding.references) return "before"; - let referencePaths: Array = binding.referencePaths; + const referencePaths: Array = binding.referencePaths; // verify that all of the references are calls - for (let path of referencePaths) { + for (const path of referencePaths) { if (path.key !== "callee" || !path.parentPath.isCallExpression()) { return; } @@ -332,13 +332,13 @@ export function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncPare let allStatus; // verify that all the calls have the same execution status - for (let path of referencePaths) { + for (const path of referencePaths) { // if a reference is a child of the function we're checking against then we can // safelty ignore it - let childOfFunction = !!path.find((path) => path.node === targetFuncPath.node); + const childOfFunction = !!path.find((path) => path.node === targetFuncPath.node); if (childOfFunction) continue; - let status = this._guessExecutionStatusRelativeTo(path); + const status = this._guessExecutionStatusRelativeTo(path); if (allStatus) { if (allStatus !== status) return; @@ -374,7 +374,7 @@ export function _resolve(dangerous?, resolved?): ?NodePath { // otherwise it's a request for a pattern and that's a bit more tricky } } else if (this.isReferencedIdentifier()) { - let binding = this.scope.getBinding(this.node.name); + const binding = this.scope.getBinding(this.node.name); if (!binding) return; // reassigned so we can't really resolve it @@ -384,7 +384,7 @@ export function _resolve(dangerous?, resolved?): ?NodePath { if (binding.kind === "module") return; if (binding.path !== this) { - let ret = binding.path.resolve(dangerous, resolved); + const ret = binding.path.resolve(dangerous, resolved); // If the identifier resolves to parent node then we can't really resolve it. if (this.find((parent) => parent.node === ret.node)) return; return ret; @@ -395,19 +395,19 @@ export function _resolve(dangerous?, resolved?): ?NodePath { // this is dangerous, as non-direct target assignments will mutate it's state // making this resolution inaccurate - let targetKey = this.toComputedKey(); + const targetKey = this.toComputedKey(); if (!t.isLiteral(targetKey)) return; - let targetName = targetKey.value; + const targetName = targetKey.value; - let target = this.get("object").resolve(dangerous, resolved); + const target = this.get("object").resolve(dangerous, resolved); if (target.isObjectExpression()) { - let props = target.get("properties"); - for (let prop of (props: Array)) { + const props = target.get("properties"); + for (const prop of (props: Array)) { if (!prop.isProperty()) continue; - let key = prop.get("key"); + const key = prop.get("key"); // { foo: obj } let match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); @@ -418,8 +418,8 @@ export function _resolve(dangerous?, resolved?): ?NodePath { if (match) return prop.get("value").resolve(dangerous, resolved); } } else if (target.isArrayExpression() && !isNaN(+targetName)) { - let elems = target.get("elements"); - let elem = elems[targetName]; + const elems = target.get("elements"); + const elem = elems[targetName]; if (elem) return elem.resolve(dangerous, resolved); } } diff --git a/packages/babel-traverse/src/path/lib/hoister.js b/packages/babel-traverse/src/path/lib/hoister.js index 3776b2d30e02..8a36031f1e79 100644 --- a/packages/babel-traverse/src/path/lib/hoister.js +++ b/packages/babel-traverse/src/path/lib/hoister.js @@ -1,14 +1,14 @@ import { react } from "babel-types"; import * as t from "babel-types"; -let referenceVisitor = { +const referenceVisitor = { ReferencedIdentifier(path, state) { if (path.isJSXIdentifier() && react.isCompatTag(path.node.name)) { return; } // direct references that we need to track to hoist this to the highest scope we can - let binding = path.scope.getBinding(path.node.name); + const binding = path.scope.getBinding(path.node.name); if (!binding) return; // this binding isn't accessible from the parent scope so we can safely ignore it @@ -18,7 +18,7 @@ let referenceVisitor = { if (binding.constant) { state.bindings[path.node.name] = binding; } else { - for (let violationPath of (binding.constantViolations: Array)) { + for (const violationPath of (binding.constantViolations: Array)) { state.breakOnScopePaths = state.breakOnScopePaths.concat(violationPath.getAncestry()); } } @@ -35,8 +35,8 @@ export default class PathHoister { } isCompatibleScope(scope) { - for (let key in this.bindings) { - let binding = this.bindings[key]; + for (const key in this.bindings) { + const binding = this.bindings[key]; if (!scope.bindingIdentifierEquals(key, binding.identifier)) { return false; } @@ -61,7 +61,7 @@ export default class PathHoister { } getAttachmentPath() { - let path = this._getAttachmentPath(); + const path = this._getAttachmentPath(); if (!path) return; let targetScope = path.scope; @@ -73,11 +73,11 @@ export default class PathHoister { // avoid hoisting to a scope that contains bindings that are executed after our attachment path if (targetScope.path.isProgram() || targetScope.path.isFunction()) { - for (let name in this.bindings) { + for (const name in this.bindings) { // check binding is a direct child of this paths scope if (!targetScope.hasOwnBinding(name)) continue; - let binding = this.bindings[name]; + const binding = this.bindings[name]; // allow parameter references if (binding.kind === "param") continue; @@ -91,9 +91,9 @@ export default class PathHoister { } _getAttachmentPath() { - let scopes = this.scopes; + const scopes = this.scopes; - let scope = scopes.pop(); + const scope = scopes.pop(); if (!scope) return; if (scope.path.isFunction()) { @@ -113,7 +113,7 @@ export default class PathHoister { } getNextScopeAttachmentParent() { - let scope = this.scopes.pop(); + const scope = this.scopes.pop(); if (scope) return this.getAttachmentParentForPath(scope.path); } @@ -127,17 +127,17 @@ export default class PathHoister { } hasOwnParamBindings(scope) { - for (let name in this.bindings) { + for (const name in this.bindings) { if (!scope.hasOwnBinding(name)) continue; - let binding = this.bindings[name]; + const binding = this.bindings[name]; if (binding.kind === "param") return true; } return false; } run() { - let node = this.path.node; + const node = this.path.node; if (node._hoisted) return; node._hoisted = true; @@ -145,7 +145,7 @@ export default class PathHoister { this.getCompatibleScopes(); - let attachTo = this.getAttachmentPath(); + const attachTo = this.getAttachmentPath(); if (!attachTo) return; // don't bother hoisting to the same function as this will cause multiple branches to be evaluated more than once leading to a bad optimisation @@ -153,13 +153,13 @@ export default class PathHoister { // generate declaration and insert it to our point let uid = attachTo.scope.generateUidIdentifier("ref"); - let declarator = t.variableDeclarator(uid, this.path.node); + const declarator = t.variableDeclarator(uid, this.path.node); attachTo.insertBefore([ attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator]) ]); - let parent = this.path.parentPath; + const parent = this.path.parentPath; if (parent.isJSXElement() && this.path.container === parent.node.children) { // turning the `span` in `
` to an expression so we need to wrap it with // an expression container diff --git a/packages/babel-traverse/src/path/lib/removal-hooks.js b/packages/babel-traverse/src/path/lib/removal-hooks.js index 07cc98ab46db..0678d1da28e0 100644 --- a/packages/babel-traverse/src/path/lib/removal-hooks.js +++ b/packages/babel-traverse/src/path/lib/removal-hooks.js @@ -4,7 +4,7 @@ * Pre hooks should be used for either rejecting removal or delegating removal */ -export let hooks = [ +export const hooks = [ function (self, parent) { let removeParent = false; diff --git a/packages/babel-traverse/src/path/lib/virtual-types.js b/packages/babel-traverse/src/path/lib/virtual-types.js index fec4dea2effd..07ba90714435 100644 --- a/packages/babel-traverse/src/path/lib/virtual-types.js +++ b/packages/babel-traverse/src/path/lib/virtual-types.js @@ -2,7 +2,7 @@ import type NodePath from "../index"; import { react } from "babel-types"; import * as t from "babel-types"; -export let ReferencedIdentifier = { +export const ReferencedIdentifier = { types: ["Identifier", "JSXIdentifier"], checkPath({ node, parent }: NodePath, opts?: Object): boolean { if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { @@ -19,21 +19,21 @@ export let ReferencedIdentifier = { } }; -export let ReferencedMemberExpression = { +export const ReferencedMemberExpression = { types: ["MemberExpression"], checkPath({ node, parent }) { return t.isMemberExpression(node) && t.isReferenced(node, parent); } }; -export let BindingIdentifier = { +export const BindingIdentifier = { types: ["Identifier"], checkPath({ node, parent }: NodePath): boolean { return t.isIdentifier(node) && t.isBinding(node, parent); } }; -export let Statement = { +export const Statement = { types: ["Statement"], checkPath({ node, parent }: NodePath): boolean { if (t.isStatement(node)) { @@ -49,7 +49,7 @@ export let Statement = { } }; -export let Expression = { +export const Expression = { types: ["Expression"], checkPath(path: NodePath): boolean { if (path.isIdentifier()) { @@ -60,51 +60,51 @@ export let Expression = { } }; -export let Scope = { +export const Scope = { types: ["Scopable"], checkPath(path) { return t.isScope(path.node, path.parent); } }; -export let Referenced = { +export const Referenced = { checkPath(path: NodePath): boolean { return t.isReferenced(path.node, path.parent); } }; -export let BlockScoped = { +export const BlockScoped = { checkPath(path: NodePath): boolean { return t.isBlockScoped(path.node); } }; -export let Var = { +export const Var = { types: ["VariableDeclaration"], checkPath(path: NodePath): boolean { return t.isVar(path.node); } }; -export let User = { +export const User = { checkPath(path: NodePath): boolean { return path.node && !!path.node.loc; } }; -export let Generated = { +export const Generated = { checkPath(path: NodePath): boolean { return !path.isUser(); } }; -export let Pure = { +export const Pure = { checkPath(path: NodePath, opts?): boolean { return path.scope.isPure(path.node, opts); } }; -export let Flow = { +export const Flow = { types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], checkPath({ node }: NodePath): boolean { if (t.isFlow(node)) { diff --git a/packages/babel-traverse/src/path/modification.js b/packages/babel-traverse/src/path/modification.js index cb4568240c6f..704014c16eeb 100644 --- a/packages/babel-traverse/src/path/modification.js +++ b/packages/babel-traverse/src/path/modification.js @@ -38,15 +38,15 @@ export function insertBefore(nodes) { export function _containerInsert(from, nodes) { this.updateSiblingKeys(from, nodes.length); - let paths = []; + const paths = []; for (let i = 0; i < nodes.length; i++) { - let to = from + i; - let node = nodes[i]; + const to = from + i; + const node = nodes[i]; this.container.splice(to, 0, node); if (this.context) { - let path = this.context.create(this.parent, this.container, to, this.listKey); + const path = this.context.create(this.parent, this.container, to, this.listKey); // While this path may have a context, there is currently no guarantee that the context // will be the active context, because `popContext` may leave a final context in place. @@ -64,13 +64,13 @@ export function _containerInsert(from, nodes) { } } - let contexts = this._getQueueContexts(); + const contexts = this._getQueueContexts(); - for (let path of paths) { + for (const path of paths) { path.setScope(); path.debug(() => "Inserted."); - for (let context of contexts) { + for (const context of contexts) { context.maybeQueue(path, true); } } @@ -87,8 +87,8 @@ export function _containerInsertAfter(nodes) { } export function _maybePopFromStatements(nodes) { - let last = nodes[nodes.length - 1]; - let isIdentifier = t.isIdentifier(last) || (t.isExpressionStatement(last) && t.isIdentifier(last.expression)); + const last = nodes[nodes.length - 1]; + const isIdentifier = t.isIdentifier(last) || (t.isExpressionStatement(last) && t.isIdentifier(last.expression)); if (isIdentifier && !this.isCompletionRecord()) { nodes.pop(); @@ -109,7 +109,7 @@ export function insertAfter(nodes) { return this.parentPath.insertAfter(nodes); } else if (this.isNodeType("Expression") || (this.parentPath.isForStatement() && this.key === "init")) { if (this.node) { - let temp = this.scope.generateDeclaredUidIdentifier(); + const temp = this.scope.generateDeclaredUidIdentifier(); nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); nodes.push(t.expressionStatement(temp)); } @@ -136,9 +136,9 @@ export function insertAfter(nodes) { export function updateSiblingKeys(fromIndex, incrementBy) { if (!this.parent) return; - let paths = pathCache.get(this.parent); + const paths = pathCache.get(this.parent); for (let i = 0; i < paths.length; i++) { - let path = paths[i]; + const path = paths[i]; if (path.key >= fromIndex) { path.key += incrementBy; } @@ -155,7 +155,7 @@ export function _verifyNodeList(nodes) { } for (let i = 0; i < nodes.length; i++) { - let node = nodes[i]; + const node = nodes[i]; let msg; if (!node) { @@ -169,7 +169,7 @@ export function _verifyNodeList(nodes) { } if (msg) { - let type = Array.isArray(node) ? "array" : typeof node; + const type = Array.isArray(node) ? "array" : typeof node; throw new Error(`Node list ${msg} with the index of ${i} and type of ${type}`); } } @@ -184,7 +184,7 @@ export function unshiftContainer(listKey, nodes) { // get the first path and insert our nodes before it, if it doesn't exist then it // doesn't matter, our nodes will be inserted anyway - let path = NodePath.get({ + const path = NodePath.get({ parentPath: this, parent: this.node, container: this.node[listKey], @@ -203,8 +203,8 @@ export function pushContainer(listKey, nodes) { // get an invisible path that represents the last node + 1 and replace it with our // nodes, effectively inlining it - let container = this.node[listKey]; - let path = NodePath.get({ + const container = this.node[listKey]; + const path = NodePath.get({ parentPath: this, parent: this.node, container: container, @@ -221,6 +221,6 @@ export function pushContainer(listKey, nodes) { */ export function hoist(scope = this.scope) { - let hoister = new PathHoister(this, scope); + const hoister = new PathHoister(this, scope); return hoister.run(); } diff --git a/packages/babel-traverse/src/path/removal.js b/packages/babel-traverse/src/path/removal.js index f7686fce6b41..76556e92eb6a 100644 --- a/packages/babel-traverse/src/path/removal.js +++ b/packages/babel-traverse/src/path/removal.js @@ -18,7 +18,7 @@ export function remove() { } export function _callRemovalHooks() { - for (let fn of (hooks: Array)) { + for (const fn of (hooks: Array)) { if (fn(this, this.parentPath)) return true; } } diff --git a/packages/babel-traverse/src/path/replacement.js b/packages/babel-traverse/src/path/replacement.js index 8ca15a4c094e..08df6ce16c94 100644 --- a/packages/babel-traverse/src/path/replacement.js +++ b/packages/babel-traverse/src/path/replacement.js @@ -7,7 +7,7 @@ import NodePath from "./index"; import { parse } from "babylon"; import * as t from "babel-types"; -let hoistVariablesVisitor = { +const hoistVariablesVisitor = { Function(path) { path.skip(); }, @@ -15,14 +15,14 @@ let hoistVariablesVisitor = { VariableDeclaration(path) { if (path.node.kind !== "var") return; - let bindings = path.getBindingIdentifiers(); - for (let key in bindings) { + const bindings = path.getBindingIdentifiers(); + for (const key in bindings) { path.scope.push({ id: bindings[key] }); } - let exprs = []; + const exprs = []; - for (let declar of (path.node.declarations: Array)) { + for (const declar of (path.node.declarations: Array)) { if (declar.init) { exprs.push(t.expressionStatement( t.assignmentExpression("=", declar.id, declar.init) @@ -73,7 +73,7 @@ export function replaceWithSourceString(replacement) { replacement = `(${replacement})`; replacement = parse(replacement); } catch (err) { - let loc = err.loc; + const loc = err.loc; if (loc) { err.message += " - make sure this is an expression."; err.message += "\n" + codeFrame(replacement, loc.line, loc.column + 1); @@ -135,7 +135,7 @@ export function replaceWith(replacement) { } } - let oldNode = this.node; + const oldNode = this.node; if (oldNode) { t.inheritsComments(replacement, oldNode); t.removeComments(oldNode); @@ -181,10 +181,10 @@ export function _replaceWith(node) { export function replaceExpressionWithStatements(nodes: Array) { this.resync(); - let toSequenceExpression = t.toSequenceExpression(nodes, this.scope); + const toSequenceExpression = t.toSequenceExpression(nodes, this.scope); if (t.isSequenceExpression(toSequenceExpression)) { - let exprs = toSequenceExpression.expressions; + const exprs = toSequenceExpression.expressions; if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { this._maybePopFromStatements(exprs); @@ -199,22 +199,22 @@ export function replaceExpressionWithStatements(nodes: Array) { } else if (toSequenceExpression) { this.replaceWith(toSequenceExpression); } else { - let container = t.functionExpression(null, [], t.blockStatement(nodes)); + const container = t.functionExpression(null, [], t.blockStatement(nodes)); container.shadow = true; this.replaceWith(t.callExpression(container, [])); this.traverse(hoistVariablesVisitor); // add implicit returns to all ending expression statements - let completionRecords: Array = this.get("callee").getCompletionRecords(); - for (let path of completionRecords) { + const completionRecords: Array = this.get("callee").getCompletionRecords(); + for (const path of completionRecords) { if (!path.isExpressionStatement()) continue; - let loop = path.findParent((path) => path.isLoop()); + const loop = path.findParent((path) => path.isLoop()); if (loop) { - let callee = this.get("callee"); + const callee = this.get("callee"); - let uid = callee.scope.generateDeclaredUidIdentifier("ret"); + const uid = callee.scope.generateDeclaredUidIdentifier("ret"); callee.get("body").pushContainer("body", t.returnStatement(uid)); path.get("expression").replaceWith( diff --git a/packages/babel-traverse/src/scope/index.js b/packages/babel-traverse/src/scope/index.js index 83e80df926a8..b7b3388b8ddb 100644 --- a/packages/babel-traverse/src/scope/index.js +++ b/packages/babel-traverse/src/scope/index.js @@ -24,9 +24,9 @@ let _crawlCallsCount = 0; */ function getCache(path, parentScope, self) { - let scopes: Array = scopeCache.get(path.node) || []; + const scopes: Array = scopeCache.get(path.node) || []; - for (let scope of scopes) { + for (const scope of scopes) { if (scope.parent === parentScope && scope.path === path) return scope; } @@ -43,7 +43,7 @@ function gatherNodeParts(node: Object, parts: Array) { if (node.source) { gatherNodeParts(node.source, parts); } else if (node.specifiers && node.specifiers.length) { - for (let specifier of (node.specifiers: Array)) { + for (const specifier of (node.specifiers: Array)) { gatherNodeParts(specifier, parts); } } else if (node.declaration) { @@ -61,7 +61,7 @@ function gatherNodeParts(node: Object, parts: Array) { } else if (t.isCallExpression(node)) { gatherNodeParts(node.callee, parts); } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { - for (let prop of (node.properties: Array)) { + for (const prop of (node.properties: Array)) { gatherNodeParts(prop.key || prop.argument, parts); } } @@ -69,10 +69,10 @@ function gatherNodeParts(node: Object, parts: Array) { // -let collectorVisitor = { +const collectorVisitor = { For(path) { - for (let key of (t.FOR_INIT_KEYS: Array)) { - let declar = path.get(key); + for (const key of (t.FOR_INIT_KEYS: Array)) { + const declar = path.get(key); if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); } }, @@ -96,7 +96,7 @@ let collectorVisitor = { }, ForXStatement(path, state) { - let left = path.get("left"); + const left = path.get("left"); if (left.isPattern() || left.isIdentifier()) { state.constantViolations.push(left); } @@ -105,18 +105,18 @@ let collectorVisitor = { ExportDeclaration: { exit(path) { const { node, scope } = path; - let declar = node.declaration; + const declar = node.declaration; if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { - let id = declar.id; + const id = declar.id; if (!id) return; - let binding = scope.getBinding(id.name); + const binding = scope.getBinding(id.name); if (binding) binding.reference(path); } else if (t.isVariableDeclaration(declar)) { - for (let decl of (declar.declarations: Array)) { - let ids = t.getBindingIdentifiers(decl); - for (let name in ids) { - let binding = scope.getBinding(name); + for (const decl of (declar.declarations: Array)) { + const ids = t.getBindingIdentifiers(decl); + for (const name in ids) { + const binding = scope.getBinding(name); if (binding) binding.reference(path); } } @@ -150,16 +150,16 @@ let collectorVisitor = { }, ClassDeclaration(path) { - let id = path.node.id; + const id = path.node.id; if (!id) return; - let name = id.name; + const name = id.name; path.scope.bindings[name] = path.scope.getBinding(name); }, Block(path) { - let paths = path.get("body"); - for (let bodyPath of (paths: Array)) { + const paths = path.get("body"); + for (const bodyPath of (paths: Array)) { if (bodyPath.isFunctionDeclaration()) { path.scope.getBlockParent().registerDeclaration(bodyPath); } @@ -181,7 +181,7 @@ export default class Scope { return parentScope; } - let cached = getCache(path, parentScope, this); + const cached = getCache(path, parentScope, this); if (cached) return cached; this.uid = uid++; @@ -225,7 +225,7 @@ export default class Scope { */ generateDeclaredUidIdentifier(name: string = "temp") { - let id = this.generateUidIdentifier(name); + const id = this.generateUidIdentifier(name); this.push({ id }); return id; } @@ -252,7 +252,7 @@ export default class Scope { i++; } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); - let program = this.getProgramParent(); + const program = this.getProgramParent(); program.references[uid] = true; program.uids[uid] = true; @@ -309,7 +309,7 @@ export default class Scope { } if (t.isIdentifier(node)) { - let binding = this.getBinding(node.name); + const binding = this.getBinding(node.name); if (binding) { return binding.constant; } else { @@ -328,7 +328,7 @@ export default class Scope { if (this.isStatic(node)) { return null; } else { - let id = this.generateUidIdentifierBasedOnNode(node); + const id = this.generateUidIdentifierBasedOnNode(node); if (!dontPush) this.push({ id }); return id; } @@ -355,7 +355,7 @@ export default class Scope { } rename(oldName: string, newName: string, block?) { - let binding = this.getBinding(oldName); + const binding = this.getBinding(oldName); if (binding) { newName = newName || this.generateUidIdentifier(oldName).name; return new Renamer(binding, oldName, newName).rename(block); @@ -370,13 +370,13 @@ export default class Scope { } dump() { - let sep = repeat("-", 60); + const sep = repeat("-", 60); console.log(sep); let scope = this; do { console.log("#", scope.block.type); - for (let name in scope.bindings) { - let binding = scope.bindings[name]; + for (const name in scope.bindings) { + const binding = scope.bindings[name]; console.log(" -", name, { constant: binding.constant, references: binding.references, @@ -389,10 +389,10 @@ export default class Scope { } toArray(node: Object, i?: number) { - let file = this.hub.file; + const file = this.hub.file; if (t.isIdentifier(node)) { - let binding = this.getBinding(node.name); + const binding = this.getBinding(node.name); if (binding && binding.constant && binding.path.isGenericType("Array")) return node; } @@ -417,7 +417,7 @@ export default class Scope { } let helperName = "toArray"; - let args = [node]; + const args = [node]; if (i === true) { helperName = "toConsumableArray"; } else if (i) { @@ -446,19 +446,19 @@ export default class Scope { } else if (path.isFunctionDeclaration()) { this.registerBinding("hoisted", path.get("id"), path); } else if (path.isVariableDeclaration()) { - let declarations = path.get("declarations"); - for (let declar of (declarations: Array)) { + const declarations = path.get("declarations"); + for (const declar of (declarations: Array)) { this.registerBinding(path.node.kind, declar); } } else if (path.isClassDeclaration()) { this.registerBinding("let", path); } else if (path.isImportDeclaration()) { - let specifiers = path.get("specifiers"); - for (let specifier of (specifiers: Array)) { + const specifiers = path.get("specifiers"); + for (const specifier of (specifiers: Array)) { this.registerBinding("module", specifier); } } else if (path.isExportDeclaration()) { - let declar = path.get("declaration"); + const declar = path.get("declaration"); if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) { this.registerDeclaration(declar); } @@ -476,9 +476,9 @@ export default class Scope { } registerConstantViolation(path: NodePath) { - let ids = path.getBindingIdentifiers(); - for (let name in ids) { - let binding = this.getBinding(name); + const ids = path.getBindingIdentifiers(); + for (const name in ids) { + const binding = this.getBinding(name); if (binding) binding.reassign(path); } } @@ -487,18 +487,18 @@ export default class Scope { if (!kind) throw new ReferenceError("no `kind`"); if (path.isVariableDeclaration()) { - let declarators: Array = path.get("declarations"); - for (let declar of declarators) { + const declarators: Array = path.get("declarations"); + for (const declar of declarators) { this.registerBinding(kind, declar); } return; } - let parent = this.getProgramParent(); - let ids = path.getBindingIdentifiers(true); + const parent = this.getProgramParent(); + const ids = path.getBindingIdentifiers(true); - for (let name in ids) { - for (let id of (ids[name]: Array)) { + for (const name in ids) { + for (const id of (ids[name]: Array)) { let local = this.getOwnBinding(name); if (local) { // same identifier so continue safely as we're likely trying to register it @@ -562,7 +562,7 @@ export default class Scope { isPure(node, constantsOnly?: boolean) { if (t.isIdentifier(node)) { - let binding = this.getBinding(node.name); + const binding = this.getBinding(node.name); if (!binding) return false; if (constantsOnly) return binding.constant; return true; @@ -570,19 +570,19 @@ export default class Scope { if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; return this.isPure(node.body, constantsOnly); } else if (t.isClassBody(node)) { - for (let method of node.body) { + for (const method of node.body) { if (!this.isPure(method, constantsOnly)) return false; } return true; } else if (t.isBinary(node)) { return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); } else if (t.isArrayExpression(node)) { - for (let elem of (node.elements: Array)) { + for (const elem of (node.elements: Array)) { if (!this.isPure(elem, constantsOnly)) return false; } return true; } else if (t.isObjectExpression(node)) { - for (let prop of (node.properties: Array)) { + for (const prop of (node.properties: Array)) { if (!this.isPure(prop, constantsOnly)) return false; } return true; @@ -615,7 +615,7 @@ export default class Scope { getData(key) { let scope = this; do { - let data = scope.data[key]; + const data = scope.data[key]; if (data != null) return data; } while (scope = scope.parent); } @@ -628,7 +628,7 @@ export default class Scope { removeData(key) { let scope = this; do { - let data = scope.data[key]; + const data = scope.data[key]; if (data != null) scope.data[key] = null; } while (scope = scope.parent); } @@ -644,7 +644,7 @@ export default class Scope { } _crawl() { - let path = this.path; + const path = this.path; // @@ -657,8 +657,8 @@ export default class Scope { // ForStatement - left, init if (path.isLoop()) { - for (let key of (t.FOR_INIT_KEYS: Array)) { - let node = path.get(key); + for (const key of (t.FOR_INIT_KEYS: Array)) { + const node = path.get(key); if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); } } @@ -682,8 +682,8 @@ export default class Scope { // Function - params, rest if (path.isFunction()) { - let params: Array = path.get("params"); - for (let param of params) { + const params: Array = path.get("params"); + for (const param of params) { this.registerBinding("param", param); } } @@ -696,10 +696,10 @@ export default class Scope { // Program - let parent = this.getProgramParent(); + const parent = this.getProgramParent(); if (parent.crawling) return; - let state = { + const state = { references: [], constantViolations: [], assignments: [], @@ -710,11 +710,11 @@ export default class Scope { this.crawling = false; // register assignments - for (let path of state.assignments) { + for (const path of state.assignments) { // register undeclared bindings as globals - let ids = path.getBindingIdentifiers(); + const ids = path.getBindingIdentifiers(); let programParent; - for (let name in ids) { + for (const name in ids) { if (path.scope.getBinding(name)) continue; programParent = programParent || path.scope.getProgramParent(); @@ -726,8 +726,8 @@ export default class Scope { } // register references - for (let ref of state.references) { - let binding = ref.scope.getBinding(ref.node.name); + for (const ref of state.references) { + const binding = ref.scope.getBinding(ref.node.name); if (binding) { binding.reference(ref); } else { @@ -736,7 +736,7 @@ export default class Scope { } // register constant violations - for (let path of state.constantViolations) { + for (const path of state.constantViolations) { path.scope.registerConstantViolation(path); } } @@ -763,15 +763,15 @@ export default class Scope { path = path.get("body"); } - let unique = opts.unique; - let kind = opts.kind || "var"; - let blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; + const unique = opts.unique; + const kind = opts.kind || "var"; + const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; - let dataKey = `declaration:${kind}:${blockHoist}`; + const dataKey = `declaration:${kind}:${blockHoist}`; let declarPath = !unique && path.getData(dataKey); if (!declarPath) { - let declar = t.variableDeclaration(kind, []); + const declar = t.variableDeclaration(kind, []); declar._generated = true; declar._blockHoist = blockHoist; @@ -779,7 +779,7 @@ export default class Scope { if (!unique) path.setData(dataKey, declarPath); } - let declarator = t.variableDeclarator(opts.id, opts.init); + const declarator = t.variableDeclarator(opts.id, opts.init); declarPath.node.declarations.push(declarator); this.registerBinding(kind, declarPath.get("declarations").pop()); } @@ -833,7 +833,7 @@ export default class Scope { */ getAllBindings(): Object { - let ids = Object.create(null); + const ids = Object.create(null); let scope = this; do { @@ -849,13 +849,13 @@ export default class Scope { */ getAllBindingsOfKind(): Object { - let ids = Object.create(null); + const ids = Object.create(null); - for (let kind of (arguments: Array)) { + for (const kind of (arguments: Array)) { let scope = this; do { - for (let name in scope.bindings) { - let binding = scope.bindings[name]; + for (const name in scope.bindings) { + const binding = scope.bindings[name]; if (binding.kind === kind) ids[name] = binding; } scope = scope.parent; @@ -884,7 +884,7 @@ export default class Scope { let scope = this; do { - let binding = scope.getOwnBinding(name); + const binding = scope.getOwnBinding(name); if (binding) return this.warnOnFlowBinding(binding); } while (scope = scope.parent); } @@ -894,12 +894,12 @@ export default class Scope { } getBindingIdentifier(name: string) { - let info = this.getBinding(name); + const info = this.getBinding(name); return info && info.identifier; } getOwnBindingIdentifier(name: string) { - let binding = this.bindings[name]; + const binding = this.bindings[name]; return binding && binding.identifier; } @@ -926,7 +926,7 @@ export default class Scope { */ moveBindingTo(name, scope) { - let info = this.getBinding(name); + const info = this.getBinding(name); if (info) { info.scope.removeOwnBinding(name); info.scope = scope; @@ -940,7 +940,7 @@ export default class Scope { removeBinding(name: string) { // clear literal binding - let info = this.getBinding(name); + const info = this.getBinding(name); if (info) { info.scope.removeOwnBinding(name); } diff --git a/packages/babel-traverse/src/scope/lib/renamer.js b/packages/babel-traverse/src/scope/lib/renamer.js index b8c1fb3b9c3f..1f05cb221a9c 100644 --- a/packages/babel-traverse/src/scope/lib/renamer.js +++ b/packages/babel-traverse/src/scope/lib/renamer.js @@ -1,7 +1,7 @@ import Binding from "../binding"; import * as t from "babel-types"; -let renameVisitor = { +const renameVisitor = { ReferencedIdentifier({ node }, state) { if (node.name === state.oldName) { node.name = state.newName; @@ -15,9 +15,9 @@ let renameVisitor = { }, "AssignmentExpression|Declaration"(path, state) { - let ids = path.getOuterBindingIdentifiers(); + const ids = path.getOuterBindingIdentifiers(); - for (let name in ids) { + for (const name in ids) { if (name === state.oldName) ids[name].name = state.newName; } } @@ -35,11 +35,11 @@ export default class Renamer { binding: Binding; maybeConvertFromExportDeclaration(parentDeclar) { - let exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; + const exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; if (!exportDeclar) return; // build specifiers that point back to this export declaration - let isDefault = exportDeclar.isExportDefaultDeclaration(); + const isDefault = exportDeclar.isExportDefaultDeclaration(); if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { @@ -48,17 +48,17 @@ export default class Renamer { parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); } - let bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); - let specifiers = []; + const bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); + const specifiers = []; - for (let name in bindingIdentifiers) { - let localName = name === this.oldName ? this.newName : name; - let exportedName = isDefault ? "default" : name; + for (const name in bindingIdentifiers) { + const localName = name === this.oldName ? this.newName : name; + const exportedName = isDefault ? "default" : name; specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); } if (specifiers.length) { - let aliasDeclar = t.exportNamedDeclaration(null, specifiers); + const aliasDeclar = t.exportNamedDeclaration(null, specifiers); // hoist to the top if it's a function if (parentDeclar.isFunctionDeclaration()) { @@ -104,10 +104,10 @@ export default class Renamer { } rename(block?) { - let { binding, oldName, newName } = this; - let { scope, path } = binding; + const { binding, oldName, newName } = this; + const { scope, path } = binding; - let parentDeclar = path.find((path) => path.isDeclaration() || path.isFunctionExpression()); + const parentDeclar = path.find((path) => path.isDeclaration() || path.isFunctionExpression()); if (parentDeclar) { this.maybeConvertFromExportDeclaration(parentDeclar); } diff --git a/packages/babel-traverse/src/visitors.js b/packages/babel-traverse/src/visitors.js index 023cdb186c2d..f8de5b791de3 100644 --- a/packages/babel-traverse/src/visitors.js +++ b/packages/babel-traverse/src/visitors.js @@ -24,16 +24,16 @@ export function explode(visitor) { visitor._exploded = true; // normalise pipes - for (let nodeType in visitor) { + for (const nodeType in visitor) { if (shouldIgnoreKey(nodeType)) continue; - let parts: Array = nodeType.split("|"); + const parts: Array = nodeType.split("|"); if (parts.length === 1) continue; - let fns = visitor[nodeType]; + const fns = visitor[nodeType]; delete visitor[nodeType]; - for (let part of parts) { + for (const part of parts) { visitor[part] = fns; } } @@ -52,15 +52,15 @@ export function explode(visitor) { ensureCallbackArrays(visitor); // add type wrappers - for (let nodeType of (Object.keys(visitor): Array)) { + for (const nodeType of (Object.keys(visitor): Array)) { if (shouldIgnoreKey(nodeType)) continue; - let wrapper = virtualTypes[nodeType]; + const wrapper = virtualTypes[nodeType]; if (!wrapper) continue; // wrap all the functions - let fns = visitor[nodeType]; - for (let type in fns) { + const fns = visitor[nodeType]; + for (const type in fns) { fns[type] = wrapCheck(wrapper, fns[type]); } @@ -68,7 +68,7 @@ export function explode(visitor) { delete visitor[nodeType]; if (wrapper.types) { - for (let type of (wrapper.types: Array)) { + for (const type of (wrapper.types: Array)) { // merge the visitor if necessary or just put it back in if (visitor[type]) { mergePair(visitor[type], fns); @@ -82,14 +82,14 @@ export function explode(visitor) { } // add aliases - for (let nodeType in visitor) { + for (const nodeType in visitor) { if (shouldIgnoreKey(nodeType)) continue; - let fns = visitor[nodeType]; + const fns = visitor[nodeType]; let aliases: ?Array = t.FLIPPED_ALIAS_KEYS[nodeType]; - let deprecratedKey = t.DEPRECATED_KEYS[nodeType]; + const deprecratedKey = t.DEPRECATED_KEYS[nodeType]; if (deprecratedKey) { console.trace(`Visitor defined for ${nodeType} but it has been renamed to ${deprecratedKey}`); aliases = [deprecratedKey]; @@ -100,8 +100,8 @@ export function explode(visitor) { // clear it from the visitor delete visitor[nodeType]; - for (let alias of aliases) { - let existing = visitor[alias]; + for (const alias of aliases) { + const existing = visitor[alias]; if (existing) { mergePair(existing, fns); } else { @@ -110,7 +110,7 @@ export function explode(visitor) { } } - for (let nodeType in visitor) { + for (const nodeType in visitor) { if (shouldIgnoreKey(nodeType)) continue; ensureCallbackArrays(visitor[nodeType]); @@ -126,7 +126,7 @@ export function verify(visitor) { throw new Error(messages.get("traverseVerifyRootFunction")); } - for (let nodeType in visitor) { + for (const nodeType in visitor) { if (nodeType === "enter" || nodeType === "exit") { validateVisitorMethods(nodeType, visitor[nodeType]); } @@ -137,9 +137,9 @@ export function verify(visitor) { throw new Error(messages.get("traverseVerifyNodeType", nodeType)); } - let visitors = visitor[nodeType]; + const visitors = visitor[nodeType]; if (typeof visitors === "object") { - for (let visitorKey in visitors) { + for (const visitorKey in visitors) { if (visitorKey === "enter" || visitorKey === "exit") { // verify that it just contains functions validateVisitorMethods(`${nodeType}.${visitorKey}`, visitors[visitorKey]); @@ -154,8 +154,8 @@ export function verify(visitor) { } function validateVisitorMethods(path, val) { - let fns = [].concat(val); - for (let fn of fns) { + const fns = [].concat(val); + for (const fn of fns) { if (typeof fn !== "function") { throw new TypeError(`Non-function found defined in ${path} with type ${typeof fn}`); } @@ -163,15 +163,15 @@ function validateVisitorMethods(path, val) { } export function merge(visitors: Array, states: Array = [], wrapper?: ?Function) { - let rootVisitor = {}; + const rootVisitor = {}; for (let i = 0; i < visitors.length; i++) { - let visitor = visitors[i]; - let state = states[i]; + const visitor = visitors[i]; + const state = states[i]; explode(visitor); - for (let type in visitor) { + for (const type in visitor) { let visitorType = visitor[type]; // if we have state or wrapper then overload the callbacks to take it @@ -179,7 +179,7 @@ export function merge(visitors: Array, states: Array = [], wrapper?: ?Function) visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); } - let nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; + const nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; mergePair(nodeVisitor, visitorType); } } @@ -188,9 +188,9 @@ export function merge(visitors: Array, states: Array = [], wrapper?: ?Function) } function wrapWithStateOrWrapper(oldVisitor, state, wrapper: ?Function) { - let newVisitor = {}; + const newVisitor = {}; - for (let key in oldVisitor) { + for (const key in oldVisitor) { let fns = oldVisitor[key]; // not an enter/exit array of callbacks @@ -219,10 +219,10 @@ function wrapWithStateOrWrapper(oldVisitor, state, wrapper: ?Function) { } function ensureEntranceObjects(obj) { - for (let key in obj) { + for (const key in obj) { if (shouldIgnoreKey(key)) continue; - let fns = obj[key]; + const fns = obj[key]; if (typeof fns === "function") { obj[key] = { enter: fns }; } @@ -235,7 +235,7 @@ function ensureCallbackArrays(obj) { } function wrapCheck(wrapper, fn) { - let newFn = function (path) { + const newFn = function (path) { if (wrapper.checkPath(path)) { return fn.apply(this, arguments); } @@ -258,7 +258,7 @@ function shouldIgnoreKey(key) { } function mergePair(dest, src) { - for (let key in src) { + for (const key in src) { dest[key] = [].concat(dest[key] || [], src[key]); } } diff --git a/packages/babel-traverse/test/ancestry.js b/packages/babel-traverse/test/ancestry.js index 43e09859ef66..8d8f01394829 100644 --- a/packages/babel-traverse/test/ancestry.js +++ b/packages/babel-traverse/test/ancestry.js @@ -1,63 +1,63 @@ -let traverse = require("../lib").default; -let assert = require("assert"); -let parse = require("babylon").parse; +const traverse = require("../lib").default; +const assert = require("assert"); +const parse = require("babylon").parse; describe("path/ancestry", function () { describe("isAncestor", function () { - let ast = parse("var a = 1; 'a';"); + const ast = parse("var a = 1; 'a';"); it("returns true if ancestor", function() { - let paths = []; + const paths = []; traverse(ast, { "Program|NumericLiteral"(path) { paths.push(path); }, }); - let [ programPath, numberPath ] = paths; + const [ programPath, numberPath ] = paths; assert(programPath.isAncestor(numberPath)); }); it("returns false if not ancestor", function() { - let paths = []; + const paths = []; traverse(ast, { "Program|NumericLiteral|StringLiteral"(path) { paths.push(path); } }); - let [ , numberPath, stringPath ] = paths; + const [ , numberPath, stringPath ] = paths; assert(!stringPath.isAncestor(numberPath)); }); }); describe("isDescendant", function () { - let ast = parse("var a = 1; 'a';"); + const ast = parse("var a = 1; 'a';"); it("returns true if descendant", function() { - let paths = []; + const paths = []; traverse(ast, { "Program|NumericLiteral"(path) { paths.push(path); }, }); - let [ programPath, numberPath ] = paths; + const [ programPath, numberPath ] = paths; assert(numberPath.isDescendant(programPath)); }); it("returns false if not descendant", function() { - let paths = []; + const paths = []; traverse(ast, { "Program|NumericLiteral|StringLiteral"(path) { paths.push(path); } }); - let [ , numberPath, stringPath ] = paths; + const [ , numberPath, stringPath ] = paths; assert(!numberPath.isDescendant(stringPath)); }); diff --git a/packages/babel-traverse/test/evaluation.js b/packages/babel-traverse/test/evaluation.js index 956d656eb3d3..3c53fbf6158e 100644 --- a/packages/babel-traverse/test/evaluation.js +++ b/packages/babel-traverse/test/evaluation.js @@ -1,9 +1,9 @@ -let traverse = require("../lib").default; -let assert = require("assert"); -let parse = require("babylon").parse; +const traverse = require("../lib").default; +const assert = require("assert"); +const parse = require("babylon").parse; function getPath(code) { - let ast = parse(code); + const ast = parse(code); let path; traverse(ast, { Program: function (_path) { diff --git a/packages/babel-traverse/test/family.js b/packages/babel-traverse/test/family.js index c6fc297f86a6..6e9a497df746 100644 --- a/packages/babel-traverse/test/family.js +++ b/packages/babel-traverse/test/family.js @@ -1,10 +1,10 @@ -let traverse = require("../lib").default; -let assert = require("assert"); -let parse = require("babylon").parse; +const traverse = require("../lib").default; +const assert = require("assert"); +const parse = require("babylon").parse; describe("path/family", function () { describe("getBindingIdentifiers", function () { - let ast = parse("var a = 1, {b} = c, [d] = e; function f() {}"); + const ast = parse("var a = 1, {b} = c, [d] = e; function f() {}"); let nodes = {}, paths = {}, outerNodes = {}, outerPaths = {}; traverse(ast, { VariableDeclaration(path) { diff --git a/packages/babel-traverse/test/scope.js b/packages/babel-traverse/test/scope.js index 332a3eabd9b9..db51118fcfe8 100644 --- a/packages/babel-traverse/test/scope.js +++ b/packages/babel-traverse/test/scope.js @@ -1,9 +1,9 @@ -let traverse = require("../lib").default; -let assert = require("assert"); -let parse = require("babylon").parse; +const traverse = require("../lib").default; +const assert = require("assert"); +const parse = require("babylon").parse; function getPath(code) { - let ast = parse(code); + const ast = parse(code); let path; traverse(ast, { Program: function (_path) { diff --git a/packages/babel-traverse/test/traverse.js b/packages/babel-traverse/test/traverse.js index cee715715059..ce87f9973ffa 100644 --- a/packages/babel-traverse/test/traverse.js +++ b/packages/babel-traverse/test/traverse.js @@ -1,23 +1,23 @@ -let traverse = require("../lib").default; -let assert = require("assert"); -let _ = require("lodash"); -let parse = require("babylon").parse; +const traverse = require("../lib").default; +const assert = require("assert"); +const _ = require("lodash"); +const parse = require("babylon").parse; describe("traverse", function () { - let code = ` + const code = ` var foo = "bar"; this.test = "wow"; `; - let ast = parse(code); - let program = ast.program; - let body = program.body; + const ast = parse(code); + const program = ast.program; + const body = program.body; it("traverse replace", function () { - let replacement = { + const replacement = { type: "StringLiteral", value: "foo" }; - let ast2 = _.cloneDeep(program); + const ast2 = _.cloneDeep(program); traverse(ast2, { enter: function (path) { @@ -29,12 +29,12 @@ describe("traverse", function () { }); it("traverse", function () { - let expect = [ + const expect = [ body[0], body[0].declarations[0], body[0].declarations[0].id, body[0].declarations[0].init, body[1], body[1].expression, body[1].expression.left, body[1].expression.left.object, body[1].expression.left.property, body[1].expression.right ]; - let actual = []; + const actual = []; traverse(program, { enter: function (path) { @@ -54,12 +54,12 @@ describe("traverse", function () { }); it("traverse blacklistTypes", function () { - let expect = [ + const expect = [ body[0], body[0].declarations[0], body[0].declarations[0].id, body[0].declarations[0].init, body[1], body[1].expression, body[1].expression.right ]; - let actual = []; + const actual = []; traverse(program, { blacklist: ["MemberExpression"], @@ -85,8 +85,8 @@ describe("traverse", function () { }); it("clearCache", function () { - let paths = []; - let scopes = []; + const paths = []; + const scopes = []; traverse(ast, { enter(path) { scopes.push(path.scope); @@ -97,8 +97,8 @@ describe("traverse", function () { traverse.clearCache(); - let paths2 = []; - let scopes2 = []; + const paths2 = []; + const scopes2 = []; traverse(ast, { enter(path) { scopes2.push(path.scope); @@ -114,7 +114,7 @@ describe("traverse", function () { }); it("clearPath", function () { - let paths = []; + const paths = []; traverse(ast, { enter(path) { paths.push(path); @@ -123,7 +123,7 @@ describe("traverse", function () { traverse.clearCache.clearPath(); - let paths2 = []; + const paths2 = []; traverse(ast, { enter(path) { paths2.push(path); @@ -136,7 +136,7 @@ describe("traverse", function () { }); it("clearScope", function () { - let scopes = []; + const scopes = []; traverse(ast, { enter(path) { scopes.push(path.scope); @@ -146,7 +146,7 @@ describe("traverse", function () { traverse.clearCache.clearScope(); - let scopes2 = []; + const scopes2 = []; traverse(ast, { enter(path) { scopes2.push(path.scope); diff --git a/packages/babel-types/src/converters.js b/packages/babel-types/src/converters.js index dcfc14d9f999..f350230ddf6d 100644 --- a/packages/babel-types/src/converters.js +++ b/packages/babel-types/src/converters.js @@ -24,10 +24,10 @@ export function toComputedKey(node: Object, key: Object = node.key || node.prope export function toSequenceExpression(nodes: Array, scope: Scope): ?Object { if (!nodes || !nodes.length) return; - let declars = []; + const declars = []; let bailed = false; - let result = convert(nodes); + const result = convert(nodes); if (bailed) return; for (let i = 0; i < declars.length; i++) { @@ -38,9 +38,9 @@ export function toSequenceExpression(nodes: Array, scope: Scope): ?Objec function convert(nodes) { let ensureLastUndefined = false; - let exprs = []; + const exprs = []; - for (let node of (nodes: Array)) { + for (const node of (nodes: Array)) { if (t.isExpression(node)) { exprs.push(node); } else if (t.isExpressionStatement(node)) { @@ -48,9 +48,9 @@ export function toSequenceExpression(nodes: Array, scope: Scope): ?Objec } else if (t.isVariableDeclaration(node)) { if (node.kind !== "var") return bailed = true; // bailed - for (let declar of (node.declarations: Array)) { - let bindings = t.getBindingIdentifiers(declar); - for (let key in bindings) { + for (const declar of (node.declarations: Array)) { + const bindings = t.getBindingIdentifiers(declar); + for (const key in bindings) { declars.push({ kind: node.kind, id: bindings[key] @@ -65,8 +65,8 @@ export function toSequenceExpression(nodes: Array, scope: Scope): ?Objec ensureLastUndefined = true; continue; } else if (t.isIfStatement(node)) { - let consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode(); - let alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode(); + const consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode(); + const alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode(); if (!consequent || !alternate) return bailed = true; exprs.push(t.conditionalExpression(node.test, consequent, alternate)); @@ -283,8 +283,8 @@ export function valueToNode(value: any): Object { // regexes if (isRegExp(value)) { - let pattern = value.source; - let flags = value.toString().match(/\/([a-z]+|)$/)[1]; + const pattern = value.source; + const flags = value.toString().match(/\/([a-z]+|)$/)[1]; return t.regExpLiteral(pattern, flags); } @@ -295,8 +295,8 @@ export function valueToNode(value: any): Object { // object if (isPlainObject(value)) { - let props = []; - for (let key in value) { + const props = []; + for (const key in value) { let nodeKey; if (t.isValidIdentifier(key)) { nodeKey = t.identifier(key); diff --git a/packages/babel-types/src/definitions/core.js b/packages/babel-types/src/definitions/core.js index 19a37158a7e2..276db2048a17 100644 --- a/packages/babel-types/src/definitions/core.js +++ b/packages/babel-types/src/definitions/core.js @@ -425,7 +425,7 @@ defineType("MemberExpression", { }, property: { validate(node, key, val) { - let expectedType = node.computed ? "Expression" : "Identifier"; + const expectedType = node.computed ? "Expression" : "Identifier"; assertNodeType(expectedType)(node, key, val); } }, @@ -489,7 +489,7 @@ defineType("ObjectMethod", { }, key: { validate(node, key, val) { - let expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + const expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; assertNodeType(...expectedTypes)(node, key, val); } }, @@ -521,7 +521,7 @@ defineType("ObjectProperty", { }, key: { validate(node, key, val) { - let expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + const expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; assertNodeType(...expectedTypes)(node, key, val); } }, diff --git a/packages/babel-types/src/definitions/es2015.js b/packages/babel-types/src/definitions/es2015.js index 4f4ff0807ce7..47c029857793 100644 --- a/packages/babel-types/src/definitions/es2015.js +++ b/packages/babel-types/src/definitions/es2015.js @@ -264,7 +264,7 @@ defineType("ClassMethod", { }, key: { validate(node, key, val) { - let expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + const expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; assertNodeType(...expectedTypes)(node, key, val); } }, diff --git a/packages/babel-types/src/definitions/index.js b/packages/babel-types/src/definitions/index.js index d4ae802350d7..17e3ca24a686 100644 --- a/packages/babel-types/src/definitions/index.js +++ b/packages/babel-types/src/definitions/index.js @@ -1,10 +1,10 @@ import * as t from "../index"; -export let VISITOR_KEYS = {}; -export let ALIAS_KEYS = {}; -export let NODE_FIELDS = {}; -export let BUILDER_KEYS = {}; -export let DEPRECATED_KEYS = {}; +export const VISITOR_KEYS = {}; +export const ALIAS_KEYS = {}; +export const NODE_FIELDS = {}; +export const BUILDER_KEYS = {}; +export const DEPRECATED_KEYS = {}; function getType(val) { if (Array.isArray(val)) { @@ -48,7 +48,7 @@ export function assertNodeType(...types: Array): Function { function validate(node, key, val) { let valid = false; - for (let type of types) { + for (const type of types) { if (t.is(type, val)) { valid = true; break; @@ -72,7 +72,7 @@ export function assertNodeOrValueType(...types: Array): Function { function validate(node, key, val) { let valid = false; - for (let type of types) { + for (const type of types) { if (getType(val) === type || t.is(type, val)) { valid = true; break; @@ -94,7 +94,7 @@ export function assertNodeOrValueType(...types: Array): Function { export function assertValueType(type: string): Function { function validate(node, key, val) { - let valid = getType(val) === type; + const valid = getType(val) === type; if (!valid) { throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); @@ -108,7 +108,7 @@ export function assertValueType(type: string): Function { export function chain(...fns: Array): Function { function validate(...args) { - for (let fn of fns) { + for (const fn of fns) { fn(...args); } } @@ -127,7 +127,7 @@ export default function defineType( deprecatedAlias?: string; } = {}, ) { - let inherits = (opts.inherits && store[opts.inherits]) || {}; + const inherits = (opts.inherits && store[opts.inherits]) || {}; opts.fields = opts.fields || inherits.fields || {}; opts.visitor = opts.visitor || inherits.visitor || []; @@ -139,12 +139,12 @@ export default function defineType( } // ensure all field keys are represented in `fields` - for (let key of (opts.visitor.concat(opts.builder): Array)) { + for (const key of (opts.visitor.concat(opts.builder): Array)) { opts.fields[key] = opts.fields[key] || {}; } - for (let key in opts.fields) { - let field = opts.fields[key]; + for (const key in opts.fields) { + const field = opts.fields[key]; if (opts.builder.indexOf(key) === -1) { field.optional = true; @@ -164,4 +164,4 @@ export default function defineType( store[type] = opts; } -let store = {}; +const store = {}; diff --git a/packages/babel-types/src/flow.js b/packages/babel-types/src/flow.js index b2dbd43dbc53..996a11c8f4fa 100644 --- a/packages/babel-types/src/flow.js +++ b/packages/babel-types/src/flow.js @@ -6,7 +6,7 @@ import * as t from "./index"; */ export function createUnionTypeAnnotation(types: Array) { - let flattened = removeTypeDuplicates(types); + const flattened = removeTypeDuplicates(types); if (flattened.length === 1) { return flattened[0]; @@ -20,16 +20,16 @@ export function createUnionTypeAnnotation(types: Array) { */ export function removeTypeDuplicates(nodes: Array): Array { - let generics = {}; - let bases = {}; + const generics = {}; + const bases = {}; // store union type groups to circular references - let typeGroups = []; + const typeGroups = []; - let types = []; + const types = []; for (let i = 0; i < nodes.length; i++) { - let node = nodes[i]; + const node = nodes[i]; if (!node) continue; // detect duplicates @@ -59,7 +59,7 @@ export function removeTypeDuplicates(nodes: Array): Array { // find a matching generic type and merge and deduplicate the type parameters if (t.isGenericTypeAnnotation(node)) { - let name = node.id.name; + const name = node.id.name; if (generics[name]) { let existing = generics[name]; @@ -83,12 +83,12 @@ export function removeTypeDuplicates(nodes: Array): Array { } // add back in bases - for (let type in bases) { + for (const type in bases) { types.push(bases[type]); } // add back in generics - for (let name in generics) { + for (const name in generics) { types.push(generics[name]); } diff --git a/packages/babel-types/src/index.js b/packages/babel-types/src/index.js index a5ae2c93257e..09cbe39ad1fc 100644 --- a/packages/babel-types/src/index.js +++ b/packages/babel-types/src/index.js @@ -4,7 +4,7 @@ import loClone from "lodash/clone"; import each from "lodash/each"; import uniq from "lodash/uniq"; -let t = exports; +const t = exports; /** * Registers `is[Type]` and `assert[Type]` generated functions for a given `type`. @@ -62,7 +62,7 @@ export { _react as react }; * Registers `is[Type]` and `assert[Type]` for all types. */ -for (let type in t.VISITOR_KEYS) { +for (const type in t.VISITOR_KEYS) { registerType(type); } @@ -74,7 +74,7 @@ t.FLIPPED_ALIAS_KEYS = {}; each(t.ALIAS_KEYS, function (aliases, type) { each(aliases, function (alias) { - let types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; + const types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; types.push(type); }); }); @@ -102,7 +102,7 @@ export const TYPES = Object.keys(t.VISITOR_KEYS) export function is(type: string, node: Object, opts?: Object): boolean { if (!node) return false; - let matches = isType(node.type, type); + const matches = isType(node.type, type); if (!matches) return false; if (typeof opts === "undefined") { @@ -123,11 +123,11 @@ export function isType(nodeType: string, targetType: string): boolean { // targetType was a primary node type, so there's no need to check the aliases. if (t.ALIAS_KEYS[targetType]) return false; - let aliases: ?Array = t.FLIPPED_ALIAS_KEYS[targetType]; + const aliases: ?Array = t.FLIPPED_ALIAS_KEYS[targetType]; if (aliases) { if (aliases[0] === nodeType) return true; - for (let alias of aliases) { + for (const alias of aliases) { if (nodeType === alias) return true; } } @@ -148,13 +148,13 @@ each(t.BUILDER_KEYS, function (keys, type) { ); } - let node = {}; + const node = {}; node.type = type; let i = 0; - for (let key of (keys: Array)) { - let field = t.NODE_FIELDS[type][key]; + for (const key of (keys: Array)) { + const field = t.NODE_FIELDS[type][key]; let arg = arguments[i++]; if (arg === undefined) arg = loClone(field.default); @@ -162,7 +162,7 @@ each(t.BUILDER_KEYS, function (keys, type) { node[key] = arg; } - for (let key in node) { + for (const key in node) { validate(node, key, node[key]); } @@ -177,8 +177,8 @@ each(t.BUILDER_KEYS, function (keys, type) { * Description */ -for (let type in t.DEPRECATED_KEYS) { - let newType = t.DEPRECATED_KEYS[type]; +for (const type in t.DEPRECATED_KEYS) { + const newType = t.DEPRECATED_KEYS[type]; function proxy(fn) { return function () { @@ -199,10 +199,10 @@ for (let type in t.DEPRECATED_KEYS) { export function validate(node?: Object, key: string, val: any) { if (!node) return; - let fields = t.NODE_FIELDS[node.type]; + const fields = t.NODE_FIELDS[node.type]; if (!fields) return; - let field = fields[key]; + const field = fields[key]; if (!field || !field.validate) return; if (field.optional && val == null) return; @@ -214,9 +214,9 @@ export function validate(node?: Object, key: string, val: any) { */ export function shallowEqual(actual: Object, expected: Object): boolean { - let keys = Object.keys(expected); + const keys = Object.keys(expected); - for (let key of (keys: Array)) { + for (const key of (keys: Array)) { if (actual[key] !== expected[key]) { return false; } @@ -260,8 +260,8 @@ export function ensureBlock(node: Object, key: string = "body"): Object { export function clone(node: Object): Object { if (!node) return node; - let newNode = {}; - for (let key in node) { + const newNode = {}; + for (const key in node) { if (key[0] === "_") continue; newNode[key] = node[key]; } @@ -273,7 +273,7 @@ export function clone(node: Object): Object { */ export function cloneWithoutLoc(node: Object): Object { - let newNode = clone(node); + const newNode = clone(node); delete newNode.loc; return newNode; } @@ -285,9 +285,9 @@ export function cloneWithoutLoc(node: Object): Object { export function cloneDeep(node: Object): Object { if (!node) return node; - let newNode = {}; + const newNode = {}; - for (let key in node) { + for (const key in node) { if (key[0] === "_") continue; let val = node[key]; @@ -315,17 +315,17 @@ export function cloneDeep(node: Object): Object { */ export function buildMatchMemberExpression(match:string, allowPartial?: boolean): Function { - let parts = match.split("."); + const parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; - let search = [member]; + const search = [member]; let i = 0; while (search.length) { - let node = search.shift(); + const node = search.shift(); if (allowPartial && i === parts.length) { return true; @@ -366,7 +366,7 @@ export function buildMatchMemberExpression(match:string, allowPartial?: boolean) */ export function removeComments(node: Object): Object { - for (let key of t.COMMENT_KEYS) { + for (const key of t.COMMENT_KEYS) { delete node[key]; } return node; @@ -409,19 +409,19 @@ export function inherits(child: Object, parent: Object): Object { if (!child || !parent) return child; // optionally inherit specific properties if not null - for (let key of (t.INHERIT_KEYS.optional: Array)) { + for (const key of (t.INHERIT_KEYS.optional: Array)) { if (child[key] == null) { child[key] = parent[key]; } } // force inherit "private" properties - for (let key in parent) { + for (const key in parent) { if (key[0] === "_") child[key] = parent[key]; } // force inherit select properties - for (let key of (t.INHERIT_KEYS.force: Array)) { + for (const key of (t.INHERIT_KEYS.force: Array)) { child[key] = parent[key]; } @@ -460,17 +460,17 @@ toFastProperties(t.VISITOR_KEYS); export function traverseFast(node: Node, enter: (node: Node) => void, opts?: Object) { if (!node) return; - let keys = t.VISITOR_KEYS[node.type]; + const keys = t.VISITOR_KEYS[node.type]; if (!keys) return; opts = opts || {}; enter(node, opts); - for (let key of keys) { - let subNode = node[key]; + for (const key of keys) { + const subNode = node[key]; if (Array.isArray(subNode)) { - for (let node of subNode) { + for (const node of subNode) { traverseFast(node, enter, opts); } } else { @@ -496,17 +496,17 @@ const CLEAR_KEYS_PLUS_COMMENTS: Array = t.COMMENT_KEYS.concat([ export function removeProperties(node: Node, opts?: Object): void { opts = opts || {}; - let map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - for (let key of map) { + const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; + for (const key of map) { if (node[key] != null) node[key] = undefined; } - for (let key in node) { + for (const key in node) { if (key[0] === "_" && node[key] != null) node[key] = undefined; } - let syms: Array = Object.getOwnPropertySymbols(node); - for (let sym of syms) { + const syms: Array = Object.getOwnPropertySymbols(node); + for (const sym of syms) { node[sym] = null; } } diff --git a/packages/babel-types/src/react.js b/packages/babel-types/src/react.js index 9b665d224d3e..ebf3829caee4 100644 --- a/packages/babel-types/src/react.js +++ b/packages/babel-types/src/react.js @@ -1,6 +1,6 @@ import * as t from "./index"; -export let isReactComponent = t.buildMatchMemberExpression("React.Component"); +export const isReactComponent = t.buildMatchMemberExpression("React.Component"); export function isCompatTag(tagName?: string): boolean { return !!tagName && /^[a-z]|\-/.test(tagName); @@ -10,7 +10,7 @@ function cleanJSXElementLiteralChild( child: { value: string }, args: Array, ) { - let lines = child.value.split(/\r\n|\n|\r/); + const lines = child.value.split(/\r\n|\n|\r/); let lastNonEmptyLine = 0; @@ -23,11 +23,11 @@ function cleanJSXElementLiteralChild( let str = ""; for (let i = 0; i < lines.length; i++) { - let line = lines[i]; + const line = lines[i]; - let isFirstLine = i === 0; - let isLastLine = i === lines.length - 1; - let isLastNonEmptyLine = i === lastNonEmptyLine; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; // replace rendered whitespace tabs with spaces let trimmedLine = line.replace(/\t/g, " "); @@ -55,7 +55,7 @@ function cleanJSXElementLiteralChild( } export function buildChildren(node: Object): Array { - let elems = []; + const elems = []; for (let i = 0; i < node.children.length; i++) { let child = node.children[i]; diff --git a/packages/babel-types/src/retrievers.js b/packages/babel-types/src/retrievers.js index c4d7647b4af9..2395ba30467a 100644 --- a/packages/babel-types/src/retrievers.js +++ b/packages/babel-types/src/retrievers.js @@ -10,17 +10,17 @@ export function getBindingIdentifiers( outerOnly?: boolean ): Object { let search = [].concat(node); - let ids = Object.create(null); + const ids = Object.create(null); while (search.length) { - let id = search.shift(); + const id = search.shift(); if (!id) continue; - let keys = t.getBindingIdentifiers.keys[id.type]; + const keys = t.getBindingIdentifiers.keys[id.type]; if (t.isIdentifier(id)) { if (duplicates) { - let _ids = ids[id.name] = ids[id.name] || []; + const _ids = ids[id.name] = ids[id.name] || []; _ids.push(id); } else { ids[id.name] = id; @@ -48,7 +48,7 @@ export function getBindingIdentifiers( if (keys) { for (let i = 0; i < keys.length; i++) { - let key = keys[i]; + const key = keys[i]; if (id[key]) { search = search.concat(id[key]); } diff --git a/packages/babel-types/src/validators.js b/packages/babel-types/src/validators.js index 78ea84cb40f8..183a304a9bdf 100644 --- a/packages/babel-types/src/validators.js +++ b/packages/babel-types/src/validators.js @@ -10,11 +10,11 @@ import { BLOCK_SCOPED_SYMBOL } from "./constants"; */ export function isBinding(node: Object, parent: Object): boolean { - let keys = getBindingIdentifiers.keys[parent.type]; + const keys = getBindingIdentifiers.keys[parent.type]; if (keys) { for (let i = 0; i < keys.length; i++) { - let key = keys[i]; - let val = parent[key]; + const key = keys[i]; + const val = parent[key]; if (Array.isArray(val)) { if (val.indexOf(node) >= 0) return true; } else { @@ -73,7 +73,7 @@ export function isReferenced(node: Object, parent: Object): boolean { case "ArrowFunctionExpression": case "FunctionDeclaration": case "FunctionExpression": - for (let param of (parent.params: Array)) { + for (const param of (parent.params: Array)) { if (param === node) return false; } @@ -254,7 +254,7 @@ export function isNodesEquivalent(a, b) { const fields = Object.keys(t.NODE_FIELDS[a.type] || a.type); - for (let field of fields) { + for (const field of fields) { if (typeof a[field] !== typeof b[field]) { return false; } diff --git a/packages/babel-types/test/cloning.js b/packages/babel-types/test/cloning.js index 817a4e1ec467..1280f94bd03f 100644 --- a/packages/babel-types/test/cloning.js +++ b/packages/babel-types/test/cloning.js @@ -1,24 +1,24 @@ -let t = require("../lib"); -let assert = require("assert"); -let parse = require("babylon").parse; +const t = require("../lib"); +const assert = require("assert"); +const parse = require("babylon").parse; suite("cloning", function () { suite("clone", function () { it("should handle undefined", function () { - let node = undefined; - let cloned = t.clone(node); + const node = undefined; + const cloned = t.clone(node); assert(cloned === undefined); }); it("should handle null", function () { - let node = null; - let cloned = t.clone(node); + const node = null; + const cloned = t.clone(node); assert(cloned === null); }); it("should handle simple cases", function () { - let node = t.arrayExpression([null, t.identifier("a")]); - let cloned = t.clone(node); + const node = t.arrayExpression([null, t.identifier("a")]); + const cloned = t.clone(node); assert(node !== cloned); assert(t.isNodesEquivalent(node, cloned) === true); }); @@ -26,42 +26,42 @@ suite("cloning", function () { suite("cloneDeep", function () { it("should handle undefined", function () { - let node = undefined; - let cloned = t.cloneDeep(node); + const node = undefined; + const cloned = t.cloneDeep(node); assert(cloned === undefined); }); it("should handle null", function () { - let node = null; - let cloned = t.cloneDeep(node); + const node = null; + const cloned = t.cloneDeep(node); assert(cloned === null); }); it("should handle simple cases", function () { - let node = t.arrayExpression([null, t.identifier("a")]); - let cloned = t.cloneDeep(node); + const node = t.arrayExpression([null, t.identifier("a")]); + const cloned = t.cloneDeep(node); assert(node !== cloned); assert(t.isNodesEquivalent(node, cloned) === true); }); it("should handle full programs", function () { - let node = parse("1 + 1"); - let cloned = t.cloneDeep(node); + const node = parse("1 + 1"); + const cloned = t.cloneDeep(node); assert(node !== cloned); assert(t.isNodesEquivalent(node, cloned) === true); }); it("should handle complex programs", function () { - let program = "'use strict'; function lol() { wow();return 1; }"; - let node = parse(program); - let cloned = t.cloneDeep(node); + const program = "'use strict'; function lol() { wow();return 1; }"; + const node = parse(program); + const cloned = t.cloneDeep(node); assert(node !== cloned); assert(t.isNodesEquivalent(node, cloned) === true); }); it("should handle missing array element", function () { - let node = parse("[,0]"); - let cloned = t.cloneDeep(node); + const node = parse("[,0]"); + const cloned = t.cloneDeep(node); assert(node !== cloned); assert(t.isNodesEquivalent(node, cloned) === true); }); diff --git a/packages/babel-types/test/validators.js b/packages/babel-types/test/validators.js index c269614f48bc..b6f6f3178211 100644 --- a/packages/babel-types/test/validators.js +++ b/packages/babel-types/test/validators.js @@ -1,14 +1,14 @@ -let t = require("../lib"); -let assert = require("assert"); -let parse = require("babylon").parse; +const t = require("../lib"); +const assert = require("assert"); +const parse = require("babylon").parse; suite("validators", function () { suite("isNodesEquivalent", function () { it("should handle simple cases", function () { - let mem = t.memberExpression(t.identifier("a"), t.identifier("b")); + const mem = t.memberExpression(t.identifier("a"), t.identifier("b")); assert(t.isNodesEquivalent(mem, mem) === true); - let mem2 = t.memberExpression(t.identifier("a"), t.identifier("c")); + const mem2 = t.memberExpression(t.identifier("a"), t.identifier("c")); assert(t.isNodesEquivalent(mem, mem2) === false); }); @@ -18,11 +18,11 @@ suite("validators", function () { }); it("should handle complex programs", function () { - let program = "'use strict'; function lol() { wow();return 1; }"; + const program = "'use strict'; function lol() { wow();return 1; }"; assert(t.isNodesEquivalent(parse(program), parse(program)) === true); - let program2 = "'use strict'; function lol() { wow();return -1; }"; + const program2 = "'use strict'; function lol() { wow();return -1; }"; assert(t.isNodesEquivalent(parse(program), parse(program2)) === false); });