react-magnetic-di
Version:
Context driven dependency injection
61 lines (50 loc) • 2.24 kB
JavaScript
var _require = require('babel-plugin-macros'),
createMacro = _require.createMacro;
var _require2 = require('./constants'),
PACKAGE_NAME = _require2.PACKAGE_NAME,
PACKAGE_FUNCTION = _require2.PACKAGE_FUNCTION,
HOC_FUNCTION = _require2.HOC_FUNCTION;
var processDIReference = require('./processor-di');
var processHOCReference = require('./processor-hoc');
var _require3 = require('./utils'),
createNamedImport = _require3.createNamedImport,
isEnabledEnv = _require3.isEnabledEnv;
var diMacro = function diMacro(_ref) {
var references = _ref.references,
babel = _ref.babel,
_ref$config = _ref.config,
config = _ref$config === void 0 ? {} : _ref$config;
var t = babel.types;
var isEnabled = isEnabledEnv() || Boolean(config.forceEnable);
var importedMethods = Object.keys(references).filter(function (v) {
return references[v].length;
});
var diImport = references[PACKAGE_FUNCTION] || [];
var hocImports = references[HOC_FUNCTION] || []; // process all di calls
diImport.forEach(function (ref) {
return processDIReference(t, ref, isEnabled);
}); // process all HOC calls
hocImports.forEach(function (ref) {
return processHOCReference(t, ref);
}); // if not enabled and only di was imported, let import to be stripped
if (importedMethods.length === 1 && importedMethods[0] === PACKAGE_FUNCTION && !isEnabled) return; // add named imports
var methodScope = references[importedMethods[0]][0].scope;
var statement = createNamedImport(t, PACKAGE_NAME, importedMethods, importedMethods.map(function (k) {
return references[k][0].node;
}));
var programPath = methodScope.getProgramParent().path;
var targetPath = programPath.get('body').find(function (p) {
return p.node && p.node.source && p.node.source.value === PACKAGE_NAME + '/macro';
});
if (targetPath) {
// if we find the macro import, we add the clean import right before
// should always be the case, but we handle exception
targetPath.insertBefore(statement);
} else {
// we add the import at the top of the program body
programPath.unshiftContainer('body', statement);
}
};
module.exports = createMacro(diMacro, {
configName: 'reactMagneticDi'
});