Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
patricklx committed Dec 18, 2024
1 parent 11487cd commit b58baec
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
25 changes: 24 additions & 1 deletion packages/macros/src/babel/macros-babel-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,32 @@ export default function main(context: typeof Babel): unknown {
// our getConfig and getOwnConfig macros are supposed to be able to absorb
// optional chaining. To make that work we need to see the optional chaining
// before preset-env compiles them away.

function fromGetConfig(path: NodePath<t.MemberExpression | t.OptionalMemberExpression> | null) {
while (path) {
const obj = path.get('object');
if (obj.isCallExpression()) {
const callee = obj.get('callee');
if (
callee.referencesImport('@embroider/macros', 'getOwnConfig') ||
callee.referencesImport('@embroider/macros', 'getGlobalConfig') ||
callee.referencesImport('@embroider/macros', 'getConfig')
) {
return true;
}
}
if (obj.isMemberExpression() || obj.isOptionalMemberExpression()) {
path = obj;
} else {
return false;
}
}
return false;
}

(visitor as any).OptionalMemberExpression = {
enter(path: NodePath<t.OptionalMemberExpression>, state: State) {
if (state.opts.mode === 'compile-time') {
if (state.opts.mode === 'compile-time' && fromGetConfig(path as any)) {
let result = new Evaluator({ state }).evaluate(path);
if (result.confident) {
path.replaceWith(buildLiterals(result.value, context));
Expand Down
2 changes: 1 addition & 1 deletion packages/macros/tests/babel/get-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ describe(`getConfig`, function () {
aKnownValue.foo = true;
result = aKnownValue?.foo;
`);
expect(code).toMatch(`result = aKnownValue?.foo`);
expect(code).toMatch(`result = aKnownValue`);
});

runTimeTest(`runtime getConfig is still present in runtime mode when using optional chaining`, () => {
Expand Down

0 comments on commit b58baec

Please sign in to comment.