kentcdodds / babel-plugin-macros

🎣 Allows you to build simple compile-time libraries
https://npm.im/babel-plugin-macros
MIT License
2.62k stars 135 forks source link

How to apply macro in live coding app (made with create-react-app) #172

Closed AmitDigga closed 3 years ago

AmitDigga commented 3 years ago

Relevant code or config


import { transform } from '@babel/core';
import macroPlugin from "babel-plugin-macros";

export function transformCode(code: string): string {
    const transformation = transform(
        `import {MyMacro} from 'my.macro';
         ${code}    // MyMacro(usage)`,
        {
            babelrc: false,
            plugins: [macroPlugin],
            filename: __filename,
        });
    return transformation?.code?.trim() ?? 'Failed to transform';
}

What you did:

I want an app where the user will write code having MyMacro in the textarea. I will use transfromCode function to apply macro and show if output code (code without macro)

Used babel transform to transform macro code to normal code using babel-plugin-macros as plugin.

What happened:

Unable to apply macro as some error related to fs package not being there or something else.

Capture3

Problem description:

Looks like when transfrom see's code with import {MyMacro} '***.macro', it tries to load that macro file, but since it a react app in web, it is unable to use fs to load that file and it causes problem.

Suggested solution:

Out of ideas. Need help :(

I think a similar thing might be used by https://astexplorer.net/ to apply macro on the web. But it's too complicated for me to understand.

AmitDigga commented 3 years ago

Hi, closing this issue. Actually, the problem can be solved without macro. Instead of macro, I can create a normal babel plugin, and perform transformation with that plugin.

conartist6 commented 2 years ago

See https://github.com/kentcdodds/babel-plugin-macros/issues/186 for additional relevant information