Defines a framework for defining macros in JS. These imports are evaluated and replaced at build-time and have zero runtime overhead. This replaces ba

heyheyhello / acorn-macros

submited by
Style Pass
2021-06-21 00:30:05

Defines a framework for defining macros in JS. These imports are evaluated and replaced at build-time and have zero runtime overhead. This replaces babel-plugin-macros and babel.

Search npm for *.acorn to find macros. This monorepo is the source of a few of them such as style.acorn, ms.acorn, and preval.acorn. You'll see JS macros published as *.macro but those are strictly for babel-plugin-macros and don't work here.

This library is very simple. It processes a single JS code-string and emits a new JS code-string. Because there's no processing of the JS module graph or understanding of files on the filesystem, your best bet is to gather your source code using a tool like esbuild and process the resulting bundle.

Read the build scripts in this repo under ./test/**/esbuild.ts for more usage examples such as combining macros, providing macro options, and using esbuild plugins to automatically externalize all *.acorn imports.

This does a single AST parse (optional) and walk to collect start/end indices for any JS identifiers that are imported by a *.acorn" import. These imports are given this identifier AST node to determine the code range (start/end) they'd like to be eval()'d on. Later, they're evaluated in the correct order to handle nested macros. Macros can run arbitrary code to perform their work, and return a new string of code to replace the macro code range.

Leave a Comment
Related Posts