Skip to content

Commit 6c24c14

Browse files
committed
feat: add new moduleFederation option
1 parent ede5558 commit 6c24c14

File tree

2 files changed

+34
-13
lines changed

2 files changed

+34
-13
lines changed

packages/babel-plugin/src/index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ const properties = [
2020

2121
const LOADABLE_COMMENT = '#__LOADABLE__'
2222

23-
const loadablePlugin = declare((api, { defaultImportSpecifier = 'loadable' }) => {
23+
const loadablePlugin = declare((api, babelOptions) => {
24+
const { defaultImportSpecifier = 'loadable' } = babelOptions
25+
2426
const { types: t } = api
2527

2628
function collectImportCallPaths(startPath) {
@@ -33,7 +35,7 @@ const loadablePlugin = declare((api, { defaultImportSpecifier = 'loadable' }) =>
3335
return imports
3436
}
3537

36-
const propertyFactories = properties.map(init => init(api))
38+
const propertyFactories = properties.map(init => init(api, babelOptions))
3739

3840
function isValidIdentifier(path, loadableImportSpecifier, lazyImportSpecifier) {
3941
// `loadable()`

packages/babel-plugin/src/properties/resolve.js

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,27 @@
11
import { getImportArg } from '../util'
22

3-
export default function resolveProperty({ types: t, template }) {
4-
const buildStatements = template`
5-
if (require.resolveWeak) {
6-
return require.resolveWeak(ID)
7-
}
8-
9-
return eval('require.resolve')(ID)
10-
`
3+
export default function resolveProperty(
4+
{ types: t, template },
5+
{ moduleFederation },
6+
) {
7+
const templates = {
8+
federated: template`
9+
require(ID)
10+
11+
if (require.resolveWeak) {
12+
return require.resolveWeak(ID)
13+
}
14+
15+
return eval('require.resolve')(ID)
16+
`,
17+
standard: template`
18+
if (require.resolveWeak) {
19+
return require.resolveWeak(ID)
20+
}
21+
22+
return eval('require.resolve')(ID)
23+
`,
24+
}
1125

1226
function getCallValue(callPath) {
1327
const importArg = getImportArg(callPath)
@@ -27,11 +41,16 @@ export default function resolveProperty({ types: t, template }) {
2741
return t.stringLiteral(importArg.node.value)
2842
}
2943

30-
return ({ callPath, funcPath }) =>
31-
t.objectMethod(
44+
return ({ callPath, funcPath }) => {
45+
const targetTemplate = moduleFederation ? 'federated' : 'standard'
46+
47+
return t.objectMethod(
3248
'method',
3349
t.identifier('resolve'),
3450
funcPath.node.params,
35-
t.blockStatement(buildStatements({ ID: getCallValue(callPath) })),
51+
t.blockStatement(
52+
templates[targetTemplate]({ ID: getCallValue(callPath) }),
53+
),
3654
)
55+
}
3756
}

0 commit comments

Comments
 (0)