Sha256: c027285e60d62c3fbc9364e32b1f33a1456af8d8bee6f10c22adeb361ce5055f

Contents?: true

Size: 1.63 KB

Versions: 9

Compression:

Stored size: 1.63 KB

Contents

const {parse} = require('@babel/parser')
// const printAST = require('ast-pretty-print')
const {createMacro} = require('../../')

module.exports = createMacro(evalMacro)

function evalMacro({references, state}) {
  references.default.forEach(referencePath => {
    if (referencePath.parentPath.type === 'TaggedTemplateExpression') {
      asTag(referencePath.parentPath.get('quasi'), state)
    } else if (referencePath.parentPath.type === 'CallExpression') {
      asFunction(referencePath.parentPath.get('arguments'), state)
    } else if (referencePath.parentPath.type === 'JSXOpeningElement') {
      asJSX(
        {
          attributes: referencePath.parentPath.get('attributes'),
          children: referencePath.parentPath.parentPath.get('children'),
        },
        state,
      )
    } else {
      // TODO: throw a helpful error message
    }
  })
}

function asTag(quasiPath) {
  const value = quasiPath.parentPath.get('quasi').evaluate().value
  quasiPath.parentPath.replaceWith(evalToAST(value))
}

function asFunction(argumentsPaths) {
  const value = argumentsPaths[0].evaluate().value
  argumentsPaths[0].parentPath.replaceWith(evalToAST(value))
}

// eslint-disable-next-line no-unused-vars
function asJSX({attributes, children}) {
  // It's a shame you cannot use evaluate() with JSX
  const value = children[0].node.value
  children[0].parentPath.replaceWith(evalToAST(value))
}

function evalToAST(value) {
  let x
  // eslint-disable-next-line
  eval(`x = ${value}`)
  return thingToAST(x)
}

function thingToAST(object) {
  const fileNode = parse(`var x = ${JSON.stringify(object)}`)
  return fileNode.program.body[0].declarations[0].init
}

Version data entries

9 entries across 9 versions & 3 rubygems

Version Path
disco_app-0.18.0 test/dummy/node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
disco_app-0.18.2 test/dummy/node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
jester-data-8.0.0 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-5.2.1 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-2.0.1 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-1.1.0 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-1.0.0 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-0.0.0.1.0 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js
ezii-os-0.0.0.0.1 node_modules/babel-plugin-macros/dist/__tests__/fixtures/eval.macro.js