0

I am working on a javaScript / react playground (something like very simple codesandbox.io) and I'm trying to figure out how to transpile the code. I was thinking of using Babel transform but the app itself is built using create-react-app so I do not have access to Babel. My question is, if I do something like the following and install Babel, will it also override how create-rect-app currently transpiles the code for the app?

// transpile.js
const babelOptions = {
  presets: [ "react", ["es2015", { "modules": false }]]
}

export default function preprocess(str) {
  const { code } = Babel.transform(str, babelOptions);

  return code;
}

EDIT:

I've since learned that I can use Babel standalone for exactly this use case! Now it's just to figure out how to configure it. I would still appreciate help but if I find a solution first I will post for others :)

cbutler
  • 833
  • 13
  • 36

1 Answers1

0

Ok so I have figured this out but it is not straight forward. I will try to add some details here in case anyone else finds it helpful.

I first needed to load Babel standalone and so I used this answer to create a custom hook to load a script:

import { useEffect } from 'react';

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;

    document.body.appendChild(script);

    console.log(`${url} script loaded`);

    return () => {
      document.body.removeChild(script);
      console.log(`${url} script removed`);
    }
  }, [url]);
};

export default useScript;

then I used it in my component like this:

import useScript from '../../../hooks/useScript';

useScript("https://unpkg.com/@babel/standalone/babel.min.js");

then I later use the code I wrote in the initial question to transpile my code.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
cbutler
  • 833
  • 13
  • 36