Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

babel-macros

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-macros

Enables zero-config, importable babel plugins

  • 0.4.1
  • npm
  • Socket score

Version published
Weekly downloads
2.4K
decreased by-65.34%
Maintainers
1
Weekly downloads
 
Created
Source

babel-macros 🎣

Enables zero-config, importable babel plugins


Build Status Code Coverage Dependencies version downloads MIT License

All Contributors PRs Welcome Donate Code of Conduct Roadmap Examples

Watch on GitHub Star on GitHub Tweet

The problem

Currently, each babel plugin in the babel ecosystem requires that you configure it individually. This is fine for things like language features, but can be frustrating overhead for libraries that allow for compile-time code transformation as an optimization.

This solution

babel-macros defines a standard interface for libraries that want to use compile-time code transformation without requiring the user to add a babel plugin to their build system (other than babel-macros, which is ideally already in place).

Expand for more details on the motivation

For instance, many css-in-js libraries have a css tagged template string function:

const styles = css`
  .red {
    color: red;
  }
`;

The function compiles your css into (for example) an object with generated class names for each of the classes you defined in your css:

console.log(styles); // { red: "1f-d34j8rn43y587t" }

This class name can be generated at runtime (in the browser), but this has some disadvantages:

  • There is cpu usage/time overhead; the client needs to run the code to generate these classes every time the page loads
  • There is code bundle size overhead; the client needs to receive a CSS parser in order to generate these class names, and shipping this makes the amount of js the client needs to parse larger.

To help solve those issues, many css-in-js libraries write their own babel plugin that generates the class names at compile-time instead of runtime:

// Before running through babel:
const styles = css`
  .red {
    color: red;
  }
`;
// After running through babel, with the library-specific plugin:
const styles = { red: "1f-d34j8rn43y587t" };

If the css-in-js library supported babel-macros instead, then they wouldn't need their own babel plugin to compile these out; they could instead rely on babel-macros to do it for them. So if a user already had babel-macros installed and configured with babel, then they wouldn't need to change their babel configuration to get the compile-time benefits of the library. This would be most useful if the boilerplate they were using came with babel-macros out of the box, which is what we're hoping will be true for create-react-app in the future.

Although css-in-js is the most common example, there are lots of other things you could use babel-macros for, like:

  • Compiling GraphQL fragments into objects so that the client doesn't need a GraphQL parser
  • Eval-ing out code at compile time that will be baked into the runtime code, for instance to get a list of directories in the filesystem (see preval)

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev babel-macros

Usage

Adding the plugin to your config

.babelrc

{
  "plugins": ["babel-macros"]
}
Via CLI
babel --plugins babel-macros script.js
Via Node API
require('babel-core').transform('code', {
  plugins: ['babel-macros'],
})
Using a macros

With the babel-macros plugin added to your config, we can now use a macros that works with the babel-macros API. Let's assume we have such a module in our project called eval.macros.js. To use it, we import or require the macros module in our code like so:

import MyEval from './eval.macros'
// or
const MyEval = require('./eval.macros')

Then we use that variable however the documentation for the macros says. Incidentally, eval.macros.js actually exists in the tests for babel-macros here and you can see how it transforms our code in the babel-macros snapshots.

Note here that the real benefit is that we don't need to configure anything for every macros you add. We simply configure babel-macros, then we can use any macros available. This is part of the benefit of using babel-macros.

Writing a macros

A macros is a JavaScript module that exports a function. It can be published to the npm registry (for generic macros, like a css-in-js library) or used locally (for domain-specific macros, like handling some special case for your company's localization efforts).

Before you write a custom macros, you might consider whether babel-plugin-preval help you do what you want as it's pretty powerful.

There are two parts to the babel-macros API:

  1. The filename convention
  2. The function you export

Filename:

The way that babel-macros determines whether to run a macros is based on the source string of the import or require statement. It must match this regex: /[./]macros(\.js)?$/ for example:

matches:

'my.macros'
'my.macros.js'
'my/macros'
'my/macros.js'

does not match:

'my-macros'
'my.macros.is-sweet'
'my/macros/rocks'

So long as your file can be required at a matching path, you're good. So you could put it in: my/macros/index.js and people would: require('my/macros') which would work fine.

If you're going to publish this to npm, the most ergonomic thing would be to name it something that ends in .macros. If it's part of a larger package, then calling the file macros.js or placing it in macros/index.js is a great way to go as well. Then people could do:

import Nice from 'nice.macros'
// or
import Sweet from 'sweet/macros'

Function API:

The macros you create should export a function. That function accepts a single parameter which is an object with the following properties:

state: The state of the file being traversed. It's the second argument you receive in a visitor function in a normal babel plugin.

references: This is an object that contains arrays of all the references to things imported from macros keyed based on the name of the import. The items in each array are the paths to the references.

Some examples:
import MyMacros from './my.macros'

MyMacros({someOption: true}, `
  some stuff
`)

// references: { default: [BabelPath] }
import {foo as FooMacros} from './my.macros'

FooMacros({someOption: true}, `
  some stuff
`)

// references: { foo: [BabelPath] }
import {foo as FooMacros} from './my.macros'

// no usage...

// references: {}

From here, it's just a matter of doing doing stuff with the BabelPaths that you're given. For that check out the babel handbook.

One other thing to note is that after your macros has run, babel-macros will remove the import/require statement for you.

Testing your macros

The best way to test your macros is using babel-plugin-tester:

import path from 'path'
import pluginTester from 'babel-plugin-tester'
import plugin from 'babel-macros'

pluginTester({
  plugin,
  snapshot: true,
  tests: withFilename([
    `
      import MyMacros from '../my.macros'

      MyMacros({someOption: true}, \`
        some stuff
      \`)
    `
  ]),
})

/*
 * This adds the filename to each test so you can do require/import relative
 * to this test file.
 */
function withFilename(tests) {
  return tests.map(t => {
    const test = {babelOptions: {filename: __filename}}
    if (typeof t === 'string') {
      test.code = t
    } else {
      Object.assign(test, t)
    }
    return test
  })
}

There is currently no way to get code coverage for your macros this way however. If you want code coverage, you'll have to call your macros yourself. Contributions to improve this experience are definitely welcome!

Inspiration

Other Solutions

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

💻 📖 🚇 ⚠️

Sunil Pai


Stephen Scott

💬 📖

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

FAQs

Package last updated on 11 Jul 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc