Search code examples
javascriptbabeljs

How does babel-standalone work?


This is a noob question. Plz explain like I'm 5.

I understand the primary concept of babel-standalone. It transpiles jsx/ES6 files into ES5 when it's loaded. However, how does it affects the way my browser interprets a script? I mean, babel-standalone itself is nothing more than a script to be translated. It's not like a browser plugin or something. When I look into the 'Sources' tab of Chrome developer tool, there still has a jsx/ES6 files not the transpiled ones. How could my browser begin to understand their syntax all of a sudden?

Thanks in advance.


Solution

    1. Listen DOM Event.

    https://github.com/babel/babel/blob/master/packages/babel-standalone/src/index.js

    // Listen for load event if we're in a browser and then kick off finding and
    // running of scripts with "text/babel" type.
    if (typeof window !== "undefined" && window?.addEventListener) {
      window.addEventListener("DOMContentLoaded", onDOMContentLoaded, false);
    }
    
    1. Get source script which is not raw javascript.

    https://github.com/babel/babel/blob/master/packages/babel-standalone/src/transformScriptTags.js

    scripts = document.getElementsByTagName("script");
    
    1. Transform from the source to raw javascript.
    2. Run by appending a script element with transformed content.
    /**
     * Appends a script element at the end of the <head> with the content of code,
     * after transforming it.
     */
    function run(transformFn, script) {
      const scriptEl = document.createElement("script");
      if (script.type) {
        scriptEl.setAttribute("type", script.type);
      }
      scriptEl.text = transformCode(transformFn, script);
      headEl.appendChild(scriptEl);
    }