• Stars
    star
    2,622
  • Rank 17,461 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎣 Allows you to build simple compile-time libraries

babel-plugin-macros 🎣

Allows you to build simple compile-time libraries


Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct

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-plugin-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-plugin-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-plugin-macros instead, then they wouldn't need their own babel plugin to compile these out; they could instead rely on babel-plugin-macros to do it for them. So if a user already had babel-plugin-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-plugin-macros out of the box, which is true for create-react-app.

Although css-in-js is the most common example, there are lots of other things you could use babel-plugin-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)

Table of Contents

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-plugin-macros

Usage

You may like to watch this YouTube video to get an idea of what macros is and how it can be used.

User docs

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

Author docs

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

Caveats

Babel cache problem

Note: This issue is not present when used in Create React App.

Most of the time you'll probably be using this with the babel cache enabled in webpack to rebuild faster. If your macro function is not pure which gets different output with same code (e.g., IO side effects) it will cause recompile mechanism fail. Unfortunately you'll also experience this problem while developing your macro as well. If there's not a change to the source code that's being transpiled, then babel will use the cache rather than running your macro again.

For now, to force recompile the code you can simply add a cache busting comment in the file:

import macro from 'non-pure.macro';

-// Do some changes of your code or
+// add a cache busting comment to force recompile.
macro('parameters');

This problem is still being worked on and is not unique to babel-plugin-macros. For more details and workarounds, please check related issues below:

FAQ

How do I find available macros?

You can write your own without publishing them to npm, but if you'd like to see existing macros you can add to your project, then take a look at the Awesome babel macros repository.

Please add any you don't see listed!

What's the difference between babel plugins and macros?

Let's use babel-plugin-console as an example.

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

  1. Add babel-plugin-console to .babelrc
  2. Use it in a code:
function add100(a) {
  const oneHundred = 100
  console.scope('Add 100 to another number')
  return add(a, oneHundred)
}

function add(a, b) {
  return a + b
}

When that code is run, the scope function does some pretty nifty things:

Browser:

Browser console scoping add100

Node:

Node console scoping add100

Instead, let's use the macro it's shipped with like this:

  1. Add babel-plugin-macros to .babelrc (only once for all macros)
  2. Use it in a code:
import scope from 'babel-plugin-console/scope.macro'
function add100(a) {
  const oneHundred = 100
  scope('Add 100 to another number')
  return add(a, oneHundred)
}

function add(a, b) {
  return a + b
}

The result is exactly the same, but this approach has a few advantages:

Advantages:

  • requires only one entry in .babelrc for all macros used in project. Add that once and you can use all the macros you want
  • toolkits (like create-react-app) may already support babel-plugin-macros, so no configuration is needed at all
  • it's explicit. With console.scope people may be fooled that it's just a normal console API when there's really a babel transpilation going on. When you import scope, it's obvious that it's macro and does something with the code at compile time. Some ESLint rules may also have issues with plugins that look for "global" variables
  • macros are safer and easier to write, because they receive exactly the AST node to process
  • If you misconfigure babel-plugin-console you wont find out until you run the code. If you misconfigure babel-plugin-macros you'll get a compile-time error.

Drawbacks:

  • Cannot (should not) be used for implicit transpilations (like syntax plugins)
  • Explicitness is more verbose. Which some people might consider a drawback...

In what order are macros executed?

This is another advantage of babel-plugin-macros over regular plugins. The user of the macro is in control of the ordering! The order of execution is the same order as imported. The order of execution is clear, explicit and in full control of the user:

import preval from 'preval.macro'
import idx from 'idx.macro'

// preval macro is evaluated first, then idx

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 function calls 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-plugin-macros designed. However, some things do need to be implicit, and those kinds of babel plugins can't be turned into macros.

Inspiration

Thank you to @phpnode for donating the npm package babel-plugin-macros.

Other Solutions

Issues

Looking to contribute? Look for the Good First Issue label.

πŸ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

πŸ’‘ Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a πŸ‘. This helps maintainers prioritize what to work on.

See Feature Requests

Contributors ✨

Thanks goes to these people (emoji key):


Kent C. Dodds

πŸ’» πŸ“– πŸš‡ ⚠️

Sunil Pai

πŸ€”

Lily Scott

πŸ’¬ πŸ“–

Michiel Dral

πŸ€”

Kye Hohenberger

πŸ€”

Mitchell Hamilton

πŸ’» ⚠️

Justin Hall

πŸ“–

Brian Pedersen

πŸ’» πŸ“–

Andrew Palm

πŸ’»

Michael Hsu

πŸ“– πŸ”Œ

Bo Lingen

πŸ’»

Tyler Haas

πŸ“–

FWeinb

πŸ’»

TomΓ‘Ε‘ Ehrlich

πŸ› πŸ’»

Jonas Gierer

πŸ“–

LoΓ―c Padier

πŸ’»

Paul Sherman

πŸ’»

Conrad Buck

πŸ’» ⚠️ πŸ“–

InvictusMB

⚠️

Eric Berry

πŸ”

Futago-za Ryuu

πŸ’» ⚠️

Luc

πŸ’»

Victor Vincent

πŸ’»

я ΠΊΠΎΡ‚ΠΈΠΊ ΠΏΡƒΡ€-ΠΏΡƒΡ€

πŸ“–

Armando Sosa

πŸ“–

Matthias

πŸ’»

Jovi De Croock

πŸ’» ⚠️

Victor Arowo

πŸ“–

Alex Chan

πŸ“–

Evan Jacobs

πŸ’»

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

LICENSE

MIT

More Repositories

1

cross-env

πŸ”€ Cross platform setting of environment scripts
JavaScript
6,313
star
2

match-sorter

Simple, expected, and deterministic best-match sorting of an array in JavaScript
TypeScript
3,719
star
3

advanced-react-patterns

This is the latest advanced react patterns workshop
JavaScript
2,885
star
4

react-hooks

Learn React Hooks! 🎣 βš›
JavaScript
2,550
star
5

bookshelf

Build a ReactJS App workshop
JavaScript
2,533
star
6

kentcdodds.com

My personal website
MDX
2,143
star
7

use-deep-compare-effect

πŸ‹ It's react's useEffect hook, except using deep comparison on the inputs, not reference equality
TypeScript
1,726
star
8

mdx-bundler

🦀 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
JavaScript
1,702
star
9

react-performance

Let's make our apps fast ⚑
JavaScript
1,557
star
10

advanced-react-patterns-v2

Created with CodeSandbox
JavaScript
1,499
star
11

testing-workshop

A workshop for learning how to test JavaScript applications
JavaScript
1,363
star
12

babel-plugin-preval

🐣 Pre-evaluate code at build-time
TypeScript
1,357
star
13

advanced-react-patterns-v1

The course material for my advanced react patterns course on Egghead.io
HTML
1,092
star
14

react-testing-library-course

Test React Components with Jest and React Testing Library on TestingJavaScript.com
JavaScript
1,004
star
15

testing-react-apps

A workshop for testing react applications
JavaScript
977
star
16

kcd-scripts

CLI toolbox for common scripts for my projects
JavaScript
870
star
17

stop-runaway-react-effects

πŸƒ Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession
JavaScript
788
star
18

netlify-shortener

Your own free URL shortener with Netlify
JavaScript
778
star
19

beginners-guide-to-react

The Beginner's Guide To ReactJS
HTML
757
star
20

react-suspense

React Suspense workshop
JavaScript
746
star
21

old-kentcdodds.com

Kent's Homepage
JavaScript
736
star
22

ng-stats

Little utility to show stats about your page's angular digest/watches.
JavaScript
657
star
23

dotfiles

Shell
510
star
24

js-testing-fundamentals

Fundamentals of Testing in JavaScript on TestingJavaScript.com
JavaScript
500
star
25

react-toggled

Component to build simple, flexible, and accessible toggle components
JavaScript
453
star
26

jest-cypress-react-babel-webpack

Configure Jest for Testing JavaScript Applications and Install, Configure, and Script Cypress for JavaScript Web Applications on TestingJavaScript.com
JavaScript
442
star
27

advanced-remix

TypeScript
393
star
28

react-testing-library-examples

Created with CodeSandbox
HTML
380
star
29

testing-node-apps

Test Node.js Backends on TestingJavaScript.com
JavaScript
365
star
30

es6-workshop

A very hands on πŸ‘ workshop πŸ’» about ES6 and beyond.
JavaScript
362
star
31

es6-todomvc

The vanillajs example converted to es6
JavaScript
353
star
32

babel-plugin-codegen

πŸ’₯ Generate code at build-time
TypeScript
347
star
33

eslint-config-kentcdodds

ESLint configuration for projects that I do... Feel free to use this!
JavaScript
338
star
34

cloc

An npm module for distributing cloc by Al Danial
JavaScript
325
star
35

asts-workshop

Improved productivity πŸ’― with the practical πŸ€“ use of the power πŸ’ͺ of Abstract Syntax Trees 🌳 to lint ⚠️ and transform πŸ”€ your code
JavaScript
295
star
36

how-jest-mocking-works

JavaScript
294
star
37

js-mocking-fundamentals

JavaScript Mocking Fundamentals on TestingJavaScript.com
JavaScript
281
star
38

webpack-config-utils

Utilities to help your webpack config be easier to read
JavaScript
262
star
39

express-app-example

How I structure Express Apps (example repo)
JavaScript
261
star
40

dom-testing-library-with-anything

Use DOM Testing Library to test any JS framework on TestingJavaScript.com
JavaScript
217
star
41

learn-react

Learn React with a laser focused, guided approach.
JavaScript
213
star
42

the-webs-next-transition

TypeScript
211
star
43

modern-react

workshop about React's hottest new features in 16.7.0
JavaScript
207
star
44

react-jest-workshop

JavaScript
199
star
45

react-github-profile

JavaScript
199
star
46

react-ava-workshop

🐯 A workshop repository for testing React βš› with AVA πŸš€ --> slides
JavaScript
192
star
47

api-check

VanillaJS version of ReactJS propTypes
JavaScript
191
star
48

starwars-names

Get a random Star Wars name
JavaScript
185
star
49

import-all.macro

A babel-macro that allows you to import all files that match a glob
JavaScript
177
star
50

remix-todomvc

An Implementation of TodoMVC with Remix
TypeScript
172
star
51

rtl-css-js

RTL for CSS in JS
JavaScript
162
star
52

react-workshop-app

An abstraction for all my React workshops
TypeScript
144
star
53

generator-kcd-oss

A yeoman generator for my open source modules
JavaScript
140
star
54

remix-workshop

TypeScript
133
star
55

issue-template

A way for github projects to make templates for github issues.
JavaScript
131
star
56

react-hooks-and-suspense-egghead-playlist

This is the code for the egghead playlist "React Hooks and Suspense"
JavaScript
128
star
57

modern-javascript

Get up to speed on the latest, most useful JavaScript features to level up your programming
JavaScript
123
star
58

kcd-discord-bot-v1

The bot for the KCD discord community
TypeScript
123
star
59

app-dev-tools

An example of how to create and hook up App DevTools to improve your development productivity of your application
JavaScript
122
star
60

preval.macro

Pre-evaluate code at build-time with babel-macros
JavaScript
120
star
61

split-guide

A tool to help generate code for workshop repositories
JavaScript
108
star
62

kcd-learning-clubs-ideas

πŸ“ Ideas for curriculum and schedule templates for KCD Learning Clubs
106
star
63

simply-react

JavaScript
104
star
64

nps-utils

Utilities for http://npm.im/nps (npm-package-scripts)
JavaScript
101
star
65

glamorous-website

This is still a work in progress
JavaScript
98
star
66

jest-glamor-react

Jest utilities for Glamor and React
JavaScript
98
star
67

react-hooks-pitfalls

The slides and code examples for my talk "React Hook Pitfalls"
JavaScript
94
star
68

webpack-validator-DEPRECATED

Use this to save yourself some time when working on a webpack configuration.
JavaScript
93
star
69

onewheel-blog

TypeScript
90
star
70

remix-tutorial-walkthrough

I live streamed working through the Remix Jokes App Tutorial
TypeScript
87
star
71

rebase-and-merge

Making this a reality ☞
JavaScript
82
star
72

managing-state-management-slides

79
star
73

css-in-js-precompiler

WORK IN PROGRESS: Precompiles CSS-in-JS objects to CSS strings
JavaScript
72
star
74

create-react-app-react-testing-library-example

JavaScript
67
star
75

10-practical-js-features

JavaScript
67
star
76

rename-gh-to-main

JavaScript
67
star
77

full-stack-components

TypeScript
66
star
78

fakebooks-remix

The Remix version of the fakebooks app demonstrated on https://remix.run. Check out the CRA version: https://github.com/kentcdodds/fakebooks-cra
TypeScript
66
star
79

cypress-testing-workshop

A workshop for learning how to write cypress tests
JavaScript
65
star
80

prettier-eslint-atom

DEPRECATED IN FAVOR OF prettier-atom + ESLint integration
JavaScript
64
star
81

repeat-todo

A simple app I made for my wife
JavaScript
63
star
82

why-react-hooks

Talk about React hooks
JavaScript
62
star
83

codegen.macro

JavaScript
61
star
84

talks

A repo with links to talks that I've given
59
star
85

quick-stack

TypeScript
57
star
86

binode

JavaScript
57
star
87

airtable-netlify-short-urls

There's a simpler version using Netlify redirects instead of Airtable here
JavaScript
57
star
88

fully-typed-web-apps-demo

TypeScript
53
star
89

argv-set-env

Set environment variables in npm scripts
JavaScript
52
star
90

react-test-context-provider

A function that allows you to specify context to pass to a child component (intended for testing only).
JavaScript
48
star
91

concurrent-react

React Suspense Egghead course
JavaScript
47
star
92

incremental-react-router-to-remix-upgrade-path

JavaScript
46
star
93

remix-mdx

JavaScript
45
star
94

setup-prettier

JavaScript
44
star
95

podcastify-dir

Take a directory of audio files and syndicate them with an rss feed
JavaScript
42
star
96

aha-programming-slides

JavaScript
42
star
97

workshop-setup

Verify and setup a repository for workshop attendees
JavaScript
42
star
98

jest-esmodules

JavaScript
40
star
99

typing-for-kids

A little app I made for my kids for Christmas :)
JavaScript
40
star
100

react-suspense-simple-example

JavaScript
39
star