import { createMacro } from 'babel-plugin-macros'; import { types } from '@babel/core'; import { ensureImport } from './helpers' type MobExprMacro = (expr: T) => T; /** * Macro version of mobx-utils/expr. * * Upon transpilation, converts `mexpr(a.b.c)` -> `computed(() => a.b.c).get()` * and ensures that `computed` is imported from MobX * * @name mexpr * @param expr Expression to be converted into a computed */ export default createMacro(({ references, state, babel: { types: t } }) => { references.default.forEach(ref => { // TODO: Extract expressions into class properties? const call_expr = ref.container as types.CallExpression; const comp_expr = call_expr.arguments[0] as any; const cf_expr = t.arrowFunctionExpression([], comp_expr); const comp_inst_expr = t.callExpression(t.identifier('computed'), [cf_expr]); const get_expr = t.memberExpression(comp_inst_expr, t.identifier('get')) const get_call_expr = t.callExpression(get_expr, []); const program = ref.scope.getProgramParent().path; ensureImport(t, program, 'computed', 'mobx') ref.parentPath.replaceWith(get_call_expr) }) }) as MobExprMacro;