Giter Site home page Giter Site logo

vpicone / babel-macros Goto Github PK

View Code? Open in Web Editor NEW

This project forked from kentcdodds/babel-plugin-macros

0.0 0.0 0.0 150 KB

๐ŸŽฃ Enables zero-config, importable babel plugins

Home Page: https://npm.im/babel-macros

License: MIT License

JavaScript 100.00%

babel-macros's Introduction

babel-macros ๐ŸŽฃ

Enables zero-config, importable babel plugins


Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Donate Code of Conduct

Watch on GitHub Star on GitHub Tweet

Sponsor

The problem

Check out this guest post on the Babel.js blog for a complete write up on the problem, motivation, and solution.

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

Are you trying to use babel-macros? Go to other/docs/user.md.

Are you trying to make your own macros that works with babel-macros? Go to other/docs/author.md. (you should probably read the user docs too).

FAQ

What's the difference between babel plugins and macros?

Suppose we have a plugin node-eval, which evaluates a node expression at compile time.

If we used babel-plugin-node-eval, it would look like this:

  1. Add babel-plugin-node-eval to .babelrc
  2. Use it in a code:
const val = nodeEval`fs.readDirSync('./fleet')`

//ย โ†“ โ†“ โ†“  compiles to  โ†“ โ†“ โ†“

const val = ['red_leader', 'blue_leader']

Instead, if there were a macro called node-eval.macro, we could use it like this:

  1. Add babel-macros to .babelrc (only once for all macros)
  2. Use it in a code:
import nodeEval from 'node-eval.macro'
const val = nodeEval`fs.readDirSync('./fleet')`

//ย โ†“ โ†“ โ†“  compiles to  โ†“ โ†“ โ†“

const val = ['red_leader', 'blue_leader']

Advantages:

  • requires only one entry in .babelrc for all macros used in project
  • boilerplates, like Create React App (soon hopefully), might already support babel-macros, so no configuration is needed
  • it's explicit, that node-eval is macro and does something with the code at compile time
  • macros are safer and easier to write, because they receive exactly the AST node to process

By the way, something like node-eval actually exists and it's called babel-plugin-preval.

In what order are macros executed?

In the same order as imported. The order of execution is clear, explicit and in full control of the user:

import nodeEval from 'node-eval.macro'
import css from 'css-in-js.macro'

# First are evaluated `node-eval` macros, then `css` macros

This differs from the current situation with babel plugins where it's prohibitively difficult to control the order plugins run in a particular file.

Does it work with tagged template literals only?

No! Any AST node type is supported.

It can be tagged template literal:

import eval from 'eval.macro'
const val = eval`7 * 6`

A function:

import eval from 'eval.macro'
const val = eval('7 * 6')

JSX Element:

import Eval from 'eval.macro'
const val = <Eval>7 * 6</Eval>

Really, anything...

See the testing snapshot for more examples.

How about implicit optimizations at compile time?

All examples above were explicit - a macro was imported and then evaluated with a specific AST node.

Completely different story are implicit babel plugins, like transform-react-constant-elements, which process whole AST tree.

Explicit is often a better pattern than implicit because it requires others to understand how things are globally configured. This is in this spirit are babel-macros designed. However, some things do need to be implicit, and those kinds of babel plugins can't be turned into macros.

Inspiration

Other Solutions

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ

Sunil Pai

๐Ÿค”

Stephen Scott

๐Ÿ’ฌ ๐Ÿ“–

Michiel Dral

๐Ÿค”

Kye Hohenberger

๐Ÿค”

Mitchell Hamilton

๐Ÿ’ป โš ๏ธ

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

LICENSE

MIT

babel-macros's People

Contributors

emmatown avatar johannes-scharlach avatar rhys-vdw avatar suchipi avatar tricoder42 avatar vpicone avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.