Skip to content

Commit

Permalink
Work around internal FB transform require() issue
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Mar 10, 2017
1 parent b34e7cf commit 0a50b6a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
3 changes: 3 additions & 0 deletions scripts/rollup/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
51 changes: 51 additions & 0 deletions scripts/rollup/fixHasteImports.js
Original file line number Diff line number Diff line change
@@ -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],
});
},
};
};

0 comments on commit 0a50b6a

Please sign in to comment.