JavaScript macros in Bun
This blog post is missing a few things from the official docs: <a href="https:&#x2F;&#x2F;bun.sh&#x2F;docs&#x2F;bundler&#x2F;macros" rel="nofollow noreferrer">https:&#x2F;&#x2F;bun.sh&#x2F;docs&#x2F;bundler&#x2F;macros</a><p>---<p>The way we do this kind of thing at Notion is very simple. We have normal CLI commands that generate code and write it to disk, and we check in those outputs. Then in CI, we run all the generation commands and verify the codegen is up-to-date. Checking in generated code means it&#x27;s really easy to understand the behavior of codegen and how it changes, and everyone gets excellent typechecking and auto-completion of codegen&#x27;d artifacts.<p>The downside to static codegen is that the &quot;templates&quot; we use for codegen need to be valid Typescript files, or we risk breakage if imports or types change.<p>Bun macros have some advantages like execution at build time for stuff like Git SHA interpolation, but because these macros can&#x27;t actually emit code, they feel <i>less</i> powerful that straight-up codegen. I could replace a lot of the Notion CLI commands with Bun macros if:<p>1. There&#x27;s a return type for macros that emits code, like:<p><pre><code>    &#x2F;&#x2F; src&#x2F;macros&#x2F;prism.ts
    export function emitPrismImports() {
      const importOrder = toposortLangagues(PRISM_LANGUAGES)
      const imports = importOrder
        .map(lang =&gt; `await import(&#x2F;* webpackChunkName: &quot;prism&quot; *&#x2F; &quot;${importPath}&quot;`)
        .join(&#x27;\n&#x27;)
      return Bun.code`${imports}`
    }

    &#x2F;&#x2F; src&#x2F;client&#x2F;syntaxHighlighting.ts
    import { emitPrismImports } from &#x27;@notionhq&#x2F;macros&#x2F;prism&#x27; with { type: &#x27;macro&#x27; }
    async function highlight(text, lang) {
      emitPrismImports()
      return Prism.highlight(text, lang)
    }
    
</code></pre>
2. There&#x27;s a way to run `bun build` and <i>just</i> do macro evaluation. I need to continue using Typescript, Webpack, Jest, etc for now, so we need eval&#x27;d macros on disk so they can be typechecked, tab-completed, and bundled by other tools.<p>The uncompiled versions still wouldn&#x27;t typecheck nicely though :thinking_face: