Write your personal code grow to be for amusing and benefit

Write your personal code grow to be for amusing and benefit

[ad_1]

If you have not heard,
babel-plugin-macros
“permits zero-config, importable babel plugins.” A couple of months in the past, I printed a
weblog publish about it at the reliable babel weblog:
“0-config code transformation with babel-plugin-macros”.

Since then, there were a couple of thrilling traits:

  1. You’ll be able to use it with a create-react-app software (v2 beta) as a result of
    it is now integrated through default within the beta model of
    babel-preset-react-app
    (which is what create-react-app v2 beta is the usage of!)
  2. It used to be added as an
    non-compulsory grow to be to astexplorer.internet through
    @FWeinb

Up till now, most effective early adopters have attempted to
write a macro,
regardless that there are a good quantity of
other folks the usage of
the rising record of
current macros. There are
lots of superior issues you’ll be able to do with babel-plugin-macros, and I wish to
devote this text to appearing you the way to get began enjoying round with
writing your personal.

Let’s get started off with a contrived macro that may break up a string of textual content and
change each area with 🐶. We’re going to name it gemmafy as a result of my canine’s title is
“Gemma.” Woof!

  1. Pass to astexplorer.internet
  2. Ensure that the language is about to JavaScript
  3. Ensure that the parser is about to babylon7
  4. Allow the grow to be and set it to babel-macros (or babel-plugin-macros
    once that is merged)

Then replica/paste this within the supply (best left) code panel:

import gemmafy from 'gemmafy.macro'

console.log(gemmafy('hi international'))

And duplicate/paste this within the grow to be (backside left) code panel:

module.exports = createMacro(gemmafyMacro)

serve as gemmafyMacro({references, state, babel}) {
  references.default.forEach(referencePath => {
    const [firstArgumentPath] = referencePath.parentPath.get('arguments')
    const stringValue = firstArgumentPath.node.price
    const gemmafied = stringValue.break up(' ').sign up for(' 🐶 ')
    const gemmafyFunctionCallPath = firstArgumentPath.parentPath
    const gemmafiedStringLiteralNode = babel.sorts.stringLiteral(gemmafied)
    gemmafyFunctionCallPath.replaceWith(gemmafiedStringLiteralNode)
  })
}

On the other hand, you’ll be able to open
this

TADA 🎉! You have written your (almost definitely) first actual babel plugin by way of a macro!

Here is the output that you simply must be seeing (within the backside proper panel):

console.log('hi 🐶 international')

You can understand that babel-plugin-macros will handle taking away the import
on the best of the report for you, and our macro changed the gemmafy name with
the string.

So this is your problem. Attempt to upload this:

console.log(gemmafy('hi international', 'international good-bye'))

Presently that’ll transpile to:

console.log('hi 🐶 international')

Your task is to make it do that as an alternative:

console.log('hi 🐶 international', 'good-bye 🐶 international')

From there, you’ll be able to mess around with it and do a large number of amusing issues!

If you wish to see extra of the features, then replica this within the supply (best
left):

import myMacro, {JSXMacro} from 'AnyNameThatEndsIn.macro'
// (observe: actually, the AnyNameThatEndsIn.macro must be the title of your package deal
// as an example: `codegen.macro`)
const functionCall = myMacro('Superior')
const jsx = <JSXMacro cool="proper!?">Hello!</JSXMacro>
const templateLiteral = myMacro`hello ${'there'}`
literallyAnythingWorks(myMacro)

And duplicate/paste this within the grow to be (backside left) code panel:

module.exports = createMacro(myMacro)

serve as myMacro({references, state, babel}) {
  // `state` is the second one argument you are handed to a customer in a
  // standard babel plugin. `babel` is the `@babel/core` module.
  // do no matter you love to the AST paths you in finding in `references`.
  // open up the console to peer what is logged and get started enjoying round!

  // references.default refers back to the default import (`myMacro` above)
  // references.JSXMacro refers back to the named import of `JSXMacro`
  const {JSXMacro = [], default: defaultImport = []} = references

  defaultImport.forEach(referencePath => {
    if (referencePath.parentPath.kind === 'TaggedTemplateExpression') {
      console.log(
        'template literal contents',
        referencePath.parentPath.get('quasi'),
      )
    } else if (referencePath.parentPath.kind === 'CallExpression') {
      if (referencePath === referencePath.parentPath.get('callee')) {
        console.log(
          'serve as name arguments (as callee)',
          referencePath.parentPath.get('arguments'),
        )
      } else if (
        referencePath.parentPath.get('arguments').comprises(referencePath)
      ) {
        console.log(
          'serve as name arguments (as argument)',
          referencePath.parentPath.get('arguments'),
        )
      }
    } else {
      // throw a useful error message or one thing :)
    }
  })

  JSXMacro.forEach(referencePath => {
    if (referencePath.parentPath.kind === 'JSXOpeningElement') {
      console.log('jsx props', {
        attributes: referencePath.parentPath.get('attributes'),
        kids: referencePath.parentPath.parentPath.get('kids'),
      })
    } else {
      // throw a useful error message or one thing :)
    }
  })
}

Subsequent, open up your developer console and try the console logs. Have amusing
with that!

On the other hand, you’ll be able to simply move
right here

Conclusion

I believe there are a LOT of truly cool puts we will move with this generation. I
did not spend any time on this e-newsletter speaking in regards to the why in the back of macros
or supplying you with concepts. I’m going to hyperlink to a couple assets for concepts under. The elemental thought
is that if there is a manner that you’ll be able to pre-compile a few of your operations, then you definitely
can strengthen runtime efficiency/package dimension of your software. As well as,
this permits you to do a little issues at construct time you probably have get right of entry to to the report
gadget. The probabilities are truly unending and we are simply getting began!
Revel in!



[ad_2]

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back To Top
0
Would love your thoughts, please comment.x
()
x