AST-based macro transforms for Rollup
Functions can improve readability. Inlining expanded constants can improve performance.
Build-time AST macros allow you to take advantge of both.
Example
Virtual DOM Example
Build-time macro for an IJK-like transform for use with hyperapp, superfine, or preact
const view =
prettier
)
Output (with const view = nodeName: 'div' attributes: {} children: nodeName: 'h1' attributes: {} children: count nodeName: 'button' attributes: children: '-' nodeName: 'button' attributes: children: '+'
CSS-in-JS Example
const css_styles = CSS` .somewhere { top: px; border: px ; } .somewhere::before { content: ""; }`
prettier
)
Output (with const css_styles = ` .somewhere { top: 120 px; border: 3 px solid color; } .somewhere::before { content: "2018-08-31T16:05"; }`;
Implementation
The heavy lifting for AST transform is provided by the excellent transform-ast
and magic-string
packages.
Macro functions are evaluated in VM2.NodeVM
isolation, providing a measure of protection from abuse.
API
MACRO(«object expression»)
Allows defining new macros and variables. A single argument of type object is expected.
The expression will be evaluated in a VM2.NodeVM
context and the result assigned to
the macro namespace. Any functions defined at the root will define new macros.
Defined macro functions
The macro's arguments are the getSource()
strings of the AST arguments nodes.
(e.g. ast_node.arguments.map(e => e.getSource())
Allowed Builtin modules:
require('os')
require('util')
require('zlib')
require('assert')
require('path')
require('url')
require('querystring')
require('punycode')
This can be customized with {vm2: {builtin: []}}
AST transformations
Additionally, this.ast_node
is the macro's CallExpression AST Node
,
enabling sophisticated AST-based transformations.
Rollup Plugin Options
// defaults:const macros = null // or {}const sandbox = null // or {}const builtin = 'os' 'util' 'zlib' 'assert' 'path' 'url' 'querystring' 'punycode' const plugins =