You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 18 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <div align="center">
  2. <h1>babel-plugin-macros 🎣</h1>
  3. Enables zero-config, importable babel plugins
  4. </div>
  5. <hr />
  6. [![Build Status][build-badge]][build]
  7. [![Code Coverage][coverage-badge]][coverage]
  8. [![version][version-badge]][package]
  9. [![downloads][downloads-badge]][npmchart]
  10. [![MIT License][license-badge]][license]
  11. [![All Contributors](https://img.shields.io/badge/all_contributors-14-orange.svg?style=flat-square)](#contributors)
  12. [![PRs Welcome][prs-badge]][prs]
  13. [![Donate][donate-badge]][donate]
  14. [![Code of Conduct][coc-badge]][coc]
  15. [![Watch on GitHub][github-watch-badge]][github-watch]
  16. [![Star on GitHub][github-star-badge]][github-star]
  17. [![Tweet][twitter-badge]][twitter]
  18. ## The problem
  19. Check out <a href="https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros" rel="nofollow">this guest post</a> on the Babel.js blog for a complete write up on the problem, motivation, and solution.
  20. Currently, each babel plugin in the babel ecosystem requires that you configure
  21. it individually. This is fine for things like language features, but can be
  22. frustrating overhead for libraries that allow for compile-time code
  23. transformation as an optimization.
  24. ## This solution
  25. babel-plugin-macros defines a standard interface for libraries that want to use
  26. compile-time code transformation without requiring the user to add a babel
  27. plugin to their build system (other than `babel-plugin-macros`, which is ideally
  28. already in place).
  29. <details>
  30. <summary>Expand for more details on the motivation</summary>
  31. For instance, many css-in-js libraries have a css tagged template string
  32. function:
  33. ```js
  34. const styles = css`
  35. .red {
  36. color: red;
  37. }
  38. `
  39. ```
  40. The function compiles your css into (for example) an object with generated class
  41. names for each of the classes you defined in your css:
  42. ```js
  43. console.log(styles) // { red: "1f-d34j8rn43y587t" }
  44. ```
  45. This class name can be generated at runtime (in the browser), but this has some
  46. disadvantages:
  47. * There is cpu usage/time overhead; the client needs to run the code to generate
  48. these classes every time the page loads
  49. * There is code bundle size overhead; the client needs to receive a CSS parser
  50. in order to generate these class names, and shipping this makes the amount of
  51. js the client needs to parse larger.
  52. To help solve those issues, many css-in-js libraries write their own babel
  53. plugin that generates the class names at compile-time instead of runtime:
  54. ```js
  55. // Before running through babel:
  56. const styles = css`
  57. .red {
  58. color: red;
  59. }
  60. `
  61. // After running through babel, with the library-specific plugin:
  62. const styles = {red: '1f-d34j8rn43y587t'}
  63. ```
  64. If the css-in-js library supported babel-plugin-macros instead, then they
  65. wouldn't need their own babel plugin to compile these out; they could instead
  66. rely on babel-plugin-macros to do it for them. So if a user already had
  67. `babel-plugin-macros` installed and configured with babel, then they wouldn't
  68. need to change their babel configuration to get the compile-time benefits of the
  69. library. This would be most useful if the boilerplate they were using came with
  70. `babel-plugin-macros` out of the box, which is true for
  71. [`create-react-app`][cra].
  72. Although css-in-js is the most common example, there are lots of other things
  73. you could use `babel-plugin-macros` for, like:
  74. * Compiling GraphQL fragments into objects so that the client doesn't need a
  75. GraphQL parser
  76. * Eval-ing out code at compile time that will be baked into the runtime code,
  77. for instance to get a list of directories in the filesystem (see
  78. [preval][preval])
  79. </details>
  80. ## Table of Contents
  81. <!-- START doctoc generated TOC please keep comment here to allow auto update -->
  82. <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
  83. * [Installation](#installation)
  84. * [Usage](#usage)
  85. * [User docs](#user-docs)
  86. * [Author docs](#author-docs)
  87. * [Caveats](#caveats)
  88. * [FAQ](#faq)
  89. * [How do I find available macros?](#how-do-i-find-available-macros)
  90. * [What's the difference between babel plugins and macros?](#whats-the-difference-between-babel-plugins-and-macros)
  91. * [In what order are macros executed?](#in-what-order-are-macros-executed)
  92. * [Does it work with function calls only?](#does-it-work-with-function-calls-only)
  93. * [How about implicit optimizations at compile time?](#how-about-implicit-optimizations-at-compile-time)
  94. * [Should macros be dependencies or devDependencies?](#should-macros-be-dependencies-or-devdependencies)
  95. * [Inspiration](#inspiration)
  96. * [Other Solutions](#other-solutions)
  97. * [Contributors](#contributors)
  98. * [LICENSE](#license)
  99. <!-- END doctoc generated TOC please keep comment here to allow auto update -->
  100. ## Installation
  101. This module is distributed via [npm][npm] which is bundled with [node][node] and
  102. should be installed as one of your project's `devDependencies`:
  103. ```
  104. npm install --save-dev babel-plugin-macros
  105. ```
  106. ## Usage
  107. > You may like to watch
  108. > [this YouTube video](https://www.youtube.com/watch?v=1queadQ0048&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u)
  109. > to get an idea of what macros is and how it can be used.
  110. ### User docs
  111. Are you trying to use `babel-plugin-macros`? Go to
  112. [`other/docs/user.md`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md).
  113. ### Author docs
  114. Are you trying to make your own macros that works with `babel-plugin-macros`? Go to
  115. [`other/docs/author.md`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/author.md).
  116. (you should probably read the user docs too).
  117. ### Caveats
  118. #### Babel cache problem
  119. 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.
  120. For now, to force recompile the code you can simply add a cache busting comment in the file:
  121. ```diff
  122. import macro from 'non-pure.macro';
  123. -// Do some changes of your code or
  124. +// add a cache busting comment to force recompile.
  125. macro('parameters');
  126. ```
  127. 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:
  128. * babel-plugin-preval: [How to force recompile? #19](https://github.com/kentcdodds/babel-plugin-preval/issues/19)
  129. * graphql.macro: [Recompile problem (babel cache) #6](https://github.com/evenchange4/graphql.macro/issues/6)
  130. ## FAQ
  131. ### How do I find available macros?
  132. You can write your own without publishing them to `npm`, but if you'd like to
  133. see existing macros you can add to your project, then take a look at
  134. [`other/docs/macros.md`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/macros.md)
  135. Please add any you don't see listed!
  136. ### What's the difference between babel plugins and macros?
  137. Let's use
  138. [`babel-plugin-console`](https://www.npmjs.com/package/babel-plugin-console) as
  139. an example.
  140. If we used `babel-plugin-console`, it would look like this:
  141. 1. Add `babel-plugin-console` to `.babelrc`
  142. 2. Use it in a code:
  143. ```js
  144. function add100(a) {
  145. const oneHundred = 100
  146. console.scope('Add 100 to another number')
  147. return add(a, oneHundred)
  148. }
  149. function add(a, b) {
  150. return a + b
  151. }
  152. ```
  153. When that code is run, the `scope` function does some pretty nifty things:
  154. **Browser:**
  155. ![Browser console scoping add100](https://github.com/mattphillips/babel-plugin-console/raw/53536cba919d5be49d4f66d957769c07ca7a4207/assets/add100-chrome.gif)
  156. **Node:**
  157. <img alt="Node console scoping add100" src="https://github.com/mattphillips/babel-plugin-console/raw/53536cba919d5be49d4f66d957769c07ca7a4207/assets/add100-node.png" width="372">
  158. Instead, let's use the macro it's shipped with like this:
  159. 1. Add `babel-plugin-macros` to `.babelrc` (only once for all macros)
  160. 2. Use it in a code:
  161. ```js
  162. import scope from 'babel-plugin-console/scope.macro'
  163. function add100(a) {
  164. const oneHundred = 100
  165. scope('Add 100 to another number')
  166. return add(a, oneHundred)
  167. }
  168. function add(a, b) {
  169. return a + b
  170. }
  171. ```
  172. The result is exactly the same, but this approach has a few advantages:
  173. **Advantages:**
  174. * requires only one entry in `.babelrc` for all macros used in project. Add that
  175. once and you can use all the macros you want
  176. * toolkits (like [create-react-app][cra]) may already support
  177. `babel-plugin-macros`, so no configuration is needed at all
  178. * it's explicit. With `console.scope` people may be fooled that it's just a
  179. normal `console` API when there's really a babel transpilation going on. When
  180. you import `scope`, it's obvious that it's macro and does something with the
  181. code at compile time. Some ESLint rules may also have issues with plugins that
  182. look for "global" variables
  183. * macros are safer and easier to write, because they receive exactly the AST
  184. node to process
  185. * If you misconfigure `babel-plugin-console` you wont find out until you run the
  186. code. If you misconfigure `babel-plugin-macros` you'll get a compile-time
  187. error.
  188. **Drawbacks:**
  189. * Cannot (should not) be used for implicit transpilations (like syntax plugins)
  190. * Explicitness is more verbose. Which some people might consider a drawback...
  191. ### In what order are macros executed?
  192. This is another advantage of `babel-plugin-macros` over regular plugins. The
  193. user of the macro is in control of the ordering! The order of execution is the
  194. same order as imported. The order of execution is clear, explicit and in full
  195. control of the user:
  196. ```js
  197. import preval from 'preval.macro'
  198. import idx from 'idx.macro'
  199. // preval macro is evaluated first, then idx
  200. ```
  201. This differs from the current situation with babel plugins where it's
  202. prohibitively difficult to control the order plugins run in a particular file.
  203. ### Does it work with function calls only?
  204. No! Any AST node type is supported.
  205. It can be tagged template literal:
  206. ```js
  207. import eval from 'eval.macro'
  208. const val = eval`7 * 6`
  209. ```
  210. A function:
  211. ```js
  212. import eval from 'eval.macro'
  213. const val = eval('7 * 6')
  214. ```
  215. JSX Element:
  216. ```js
  217. import Eval from 'eval.macro'
  218. const val = <Eval>7 * 6</Eval>
  219. ```
  220. Really, anything...
  221. See the [testing snapshot](https://github.com/kentcdodds/babel-plugin-macros/blob/master/src/__tests__/__snapshots__/index.js.snap) for more examples.
  222. ### How about implicit optimizations at compile time?
  223. All examples above were _explicit_ - a macro was imported and then evaluated
  224. with a specific AST node.
  225. Completely different story are _implicit_ babel plugins, like
  226. [transform-react-constant-elements](https://babeljs.io/docs/plugins/transform-react-constant-elements/),
  227. which process whole AST tree.
  228. Explicit is often a better pattern than implicit because it requires others to
  229. understand how things are globally configured. This is in this spirit are
  230. `babel-plugin-macros` designed. However, some things _do_ need to be implicit,
  231. and those kinds of babel plugins can't be turned into macros.
  232. ### Should macros be dependencies or devDependencies?
  233. Macros are processed at build-time and not required at runtime. They should be devDependencies.
  234. ## Inspiration
  235. * [threepointone/babel-plugin-macros](https://github.com/threepointone/babel-plugin-macros)
  236. * [facebookincubator/create-react-app#2730][cra-issue]
  237. Thank you to [@phpnode](https://github.com/phpnode) for donating the npm package
  238. `babel-plugin-macros`.
  239. ## Other Solutions
  240. * [sweetjs](http://sweetjs.org/)
  241. ## Contributors
  242. Thanks goes to these people ([emoji key][emojis]):
  243. <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
  244. <!-- prettier-ignore -->
  245. | [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds "Tests") | [<img src="https://avatars1.githubusercontent.com/u/18808?v=3" width="100px;"/><br /><sub><b>Sunil Pai</b></sub>](https://github.com/threepointone)<br />[🤔](#ideas-threepointone "Ideas, Planning, & Feedback") | [<img src="https://avatars3.githubusercontent.com/u/1341513?v=3" width="100px;"/><br /><sub><b>Stephen Scott</b></sub>](http://suchipi.com/)<br />[💬](#question-suchipi "Answering Questions") [📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=suchipi "Documentation") | [<img src="https://avatars1.githubusercontent.com/u/767261?v=4" width="100px;"/><br /><sub><b>Michiel Dral</b></sub>](http://twitter.com/dralletje)<br />[🤔](#ideas-dralletje "Ideas, Planning, & Feedback") | [<img src="https://avatars2.githubusercontent.com/u/662750?v=4" width="100px;"/><br /><sub><b>Kye Hohenberger</b></sub>](https://github.com/tkh44)<br />[🤔](#ideas-tkh44 "Ideas, Planning, & Feedback") | [<img src="https://avatars1.githubusercontent.com/u/11481355?v=4" width="100px;"/><br /><sub><b>Mitchell Hamilton</b></sub>](https://hamil.town)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=mitchellhamilton "Code") [⚠️](https://github.com/kentcdodds/babel-plugin-macros/commits?author=mitchellhamilton "Tests") | [<img src="https://avatars1.githubusercontent.com/u/1288694?v=4" width="100px;"/><br /><sub><b>Justin Hall</b></sub>](https://github.com/wKovacs64)<br />[📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=wKovacs64 "Documentation") |
  246. | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
  247. | [<img src="https://avatars3.githubusercontent.com/u/1903016?v=4" width="100px;"/><br /><sub><b>Brian Pedersen</b></sub>](https://github.com/PiereDome)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=PiereDome "Code") [📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=PiereDome "Documentation") | [<img src="https://avatars3.githubusercontent.com/u/4495237?v=4" width="100px;"/><br /><sub><b>Andrew Palm</b></sub>](https://github.com/apalm)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=apalm "Code") | [<img src="https://avatars1.githubusercontent.com/u/1527371?v=4" width="100px;"/><br /><sub><b>Michael Hsu</b></sub>](https://michaelhsu.tw/)<br />[📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=evenchange4 "Documentation") [🔌](#plugin-evenchange4 "Plugin/utility libraries") | [<img src="https://avatars2.githubusercontent.com/u/16605186?v=4" width="100px;"/><br /><sub><b>Bo Lingen</b></sub>](https://github.com/citycide)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=citycide "Code") | [<img src="https://avatars1.githubusercontent.com/u/11150235?v=4" width="100px;"/><br /><sub><b>Tyler Haas</b></sub>](https://github.com/tylerthehaas)<br />[📖](https://github.com/kentcdodds/babel-plugin-macros/commits?author=tylerthehaas "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/1250430?v=4" width="100px;"/><br /><sub><b>FWeinb</b></sub>](https://github.com/FWeinb)<br />[💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=FWeinb "Code") | [<img src="https://avatars2.githubusercontent.com/u/827862?v=4" width="100px;"/><br /><sub><b>Tomáš Ehrlich</b></sub>](http://www.tomasehrlich.cz)<br />[🐛](https://github.com/kentcdodds/babel-plugin-macros/issues?q=author%3Atricoder42 "Bug reports") [💻](https://github.com/kentcdodds/babel-plugin-macros/commits?author=tricoder42 "Code") |
  248. <!-- ALL-CONTRIBUTORS-LIST:END -->
  249. This project follows the [all-contributors][all-contributors] specification.
  250. Contributions of any kind welcome!
  251. ## LICENSE
  252. MIT
  253. [npm]: https://www.npmjs.com/
  254. [node]: https://nodejs.org
  255. [build-badge]: https://img.shields.io/travis/kentcdodds/babel-plugin-macros.svg?style=flat-square
  256. [build]: https://travis-ci.org/kentcdodds/babel-plugin-macros
  257. [coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/babel-plugin-macros.svg?style=flat-square
  258. [coverage]: https://codecov.io/github/kentcdodds/babel-plugin-macros
  259. [version-badge]: https://img.shields.io/npm/v/babel-plugin-macros.svg?style=flat-square
  260. [package]: https://www.npmjs.com/package/babel-plugin-macros
  261. [downloads-badge]: https://img.shields.io/npm/dm/babel-plugin-macros.svg?style=flat-square
  262. [npmchart]: http://npmcharts.com/compare/babel-plugin-macros
  263. [license-badge]: https://img.shields.io/npm/l/babel-plugin-macros.svg?style=flat-square
  264. [license]: https://github.com/kentcdodds/babel-plugin-macros/blob/master/LICENSE
  265. [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
  266. [prs]: http://makeapullrequest.com
  267. [donate-badge]: https://img.shields.io/badge/$-support-green.svg?style=flat-square
  268. [donate]: http://kcd.im/donate
  269. [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
  270. [coc]: https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/CODE_OF_CONDUCT.md
  271. [github-watch-badge]: https://img.shields.io/github/watchers/kentcdodds/babel-plugin-macros.svg?style=social
  272. [github-watch]: https://github.com/kentcdodds/babel-plugin-macros/watchers
  273. [github-star-badge]: https://img.shields.io/github/stars/kentcdodds/babel-plugin-macros.svg?style=social
  274. [github-star]: https://github.com/kentcdodds/babel-plugin-macros/stargazers
  275. [twitter]: https://twitter.com/intent/tweet?text=Check%20out%20babel-plugin-macros!%20https://github.com/kentcdodds/babel-plugin-macros%20%F0%9F%91%8D
  276. [twitter-badge]: https://img.shields.io/twitter/url/https/github.com/kentcdodds/babel-plugin-macros.svg?style=social
  277. [emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
  278. [all-contributors]: https://github.com/kentcdodds/all-contributors
  279. [preval]: https://github.com/kentcdodds/babel-plugin-preval
  280. [cra]: https://github.com/facebookincubator/create-react-app
  281. [cra-issue]: https://github.com/facebookincubator/create-react-app/issues/2730