From 6c24c149ed773f742802696c150f9a96eb0a192c Mon Sep 17 00:00:00 2001 From: Bruno Silva Date: Thu, 15 Dec 2022 14:49:57 -0300 Subject: [PATCH] feat: add new moduleFederation option --- packages/babel-plugin/src/index.js | 6 ++- .../babel-plugin/src/properties/resolve.js | 41 ++++++++++++++----- 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/packages/babel-plugin/src/index.js b/packages/babel-plugin/src/index.js index 24081f419..c5b5829c6 100644 --- a/packages/babel-plugin/src/index.js +++ b/packages/babel-plugin/src/index.js @@ -20,7 +20,9 @@ const properties = [ const LOADABLE_COMMENT = '#__LOADABLE__' -const loadablePlugin = declare((api, { defaultImportSpecifier = 'loadable' }) => { +const loadablePlugin = declare((api, babelOptions) => { + const { defaultImportSpecifier = 'loadable' } = babelOptions + const { types: t } = api function collectImportCallPaths(startPath) { @@ -33,7 +35,7 @@ const loadablePlugin = declare((api, { defaultImportSpecifier = 'loadable' }) => return imports } - const propertyFactories = properties.map(init => init(api)) + const propertyFactories = properties.map(init => init(api, babelOptions)) function isValidIdentifier(path, loadableImportSpecifier, lazyImportSpecifier) { // `loadable()` diff --git a/packages/babel-plugin/src/properties/resolve.js b/packages/babel-plugin/src/properties/resolve.js index 8c952d0df..5eca5d6c0 100644 --- a/packages/babel-plugin/src/properties/resolve.js +++ b/packages/babel-plugin/src/properties/resolve.js @@ -1,13 +1,27 @@ import { getImportArg } from '../util' -export default function resolveProperty({ types: t, template }) { - const buildStatements = template` - if (require.resolveWeak) { - return require.resolveWeak(ID) - } - - return eval('require.resolve')(ID) - ` +export default function resolveProperty( + { types: t, template }, + { moduleFederation }, +) { + const templates = { + federated: template` + require(ID) + + if (require.resolveWeak) { + return require.resolveWeak(ID) + } + + return eval('require.resolve')(ID) + `, + standard: template` + if (require.resolveWeak) { + return require.resolveWeak(ID) + } + + return eval('require.resolve')(ID) + `, + } function getCallValue(callPath) { const importArg = getImportArg(callPath) @@ -27,11 +41,16 @@ export default function resolveProperty({ types: t, template }) { return t.stringLiteral(importArg.node.value) } - return ({ callPath, funcPath }) => - t.objectMethod( + return ({ callPath, funcPath }) => { + const targetTemplate = moduleFederation ? 'federated' : 'standard' + + return t.objectMethod( 'method', t.identifier('resolve'), funcPath.node.params, - t.blockStatement(buildStatements({ ID: getCallValue(callPath) })), + t.blockStatement( + templates[targetTemplate]({ ID: getCallValue(callPath) }), + ), ) + } }