From 0a50b6a90bffc59f8f5416ef36000b5e3a44d253 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Fri, 10 Mar 2017 14:26:28 +0000 Subject: [PATCH] Work around internal FB transform require() issue --- scripts/rollup/build.js | 3 ++ scripts/rollup/fixHasteImports.js | 51 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 scripts/rollup/fixHasteImports.js diff --git a/scripts/rollup/build.js b/scripts/rollup/build.js index 2c3911e2e21b9..3fa92b223069d 100644 --- a/scripts/rollup/build.js +++ b/scripts/rollup/build.js @@ -10,6 +10,7 @@ const replace = require('rollup-plugin-replace'); const chalk = require('chalk'); const boxen = require('boxen'); const { resolve } = require('path'); +const fixHasteImports = require('./fixHasteImports'); const { createModuleMap, getExternalModules, @@ -181,6 +182,8 @@ function getPlugins(entry, babelOpts, paths, filename, bundleType) { stripEnvVariables(false) ) ); + } else if (bundleType === bundleTypes.FB) { + plugins.push(fixHasteImports()); } // this needs to come last or it doesn't report sizes correctly plugins.push( diff --git a/scripts/rollup/fixHasteImports.js b/scripts/rollup/fixHasteImports.js new file mode 100644 index 0000000000000..8c242a9c19075 --- /dev/null +++ b/scripts/rollup/fixHasteImports.js @@ -0,0 +1,51 @@ +const { transform } = require('babel-core'); + +// This makes sure top-level requires() are bound +// to variable names matching the module names. +// This is necessary to stop FB internal require +// transform from complaining. +function fixImportsTransform(babel) { + const { types: t } = babel; + return { + visitor: { + Program(path) { + const topLevelVars = path.node.body.filter(node => + node.type === 'VariableDeclaration' && + node.declarations.length === 1 && + node.declarations[0].init && + node.declarations[0].init.type === 'CallExpression' && + node.declarations[0].init.callee.name === 'require' + ); + topLevelVars.forEach(v => { + let moduleName = v.declarations[0].init.arguments[0].value; + const slashIndex = moduleName.lastIndexOf('/'); + if (slashIndex !== -1) { + moduleName = moduleName.slice(slashIndex + 1); + } + const name = v.declarations[0].id.name; + if (moduleName === name) { + return; + } + // Names don't match. This means Rollup + // already uses this name for another variable + // in the global scope. Swap them so that declaration + // matches the module name. + path.scope.rename(moduleName); + path.scope.rename(name, moduleName); + }); + }, + }, + }; +} + +module.exports = function fixHasteImports() { + return { + name: 'fix-haste-imports', + transformBundle(code) { + return transform(code, { + compact: false, + plugins: [fixImportsTransform], + }); + }, + }; +};