简体   繁体   中英

how is the transpiling language of a script chosen by the browser

Recently i have been working with code that imports babel as a script

<script src="https://unpkg.com/@babel/standalone@7.9.3/babel.js"></script>

and then uses the type text/babel in a script below to be able to write jsx.

<script type="text/babel">

 // some jsx code

</script>

I wonder how that type is recognized by the browser who decides to use the previously imported babel to transpile the code.

I always assumed the browser had a set of default script types that it knew how to handle -- and it does -- but text/babel is clearly not one of them.

So how does this work?

I just looked inside the babel.js file and it became obvious.

var scriptTypes = ['text/babel','text/jsx'];

[....]

function runScripts(transformFn, scripts) {
    headEl = document.getElementsByTagName("head")[0];

    if (!scripts) {
      scripts = document.getElementsByTagName("script");
    }

    var jsxScripts = [];

    for (var i = 0; i < scripts.length; i++) {
      var script = scripts.item(i);
      var type = script.type.split(";")[0];

      if (scriptTypes.indexOf(type) !== -1) {
        jsxScripts.push(script);
      }
    }

    if (jsxScripts.length === 0) {
      return;
    }

    console.warn("You are using the in-browser Babel transformer. Be sure to precompile " + "your scripts for production - https://babeljs.io/docs/setup/");
    loadScripts(transformFn, jsxScripts);
  }

the babel script runs before the text/babel script and it finds all text/babel scripts, transpiles them and runs them. So the browser doesn't need to be aware of that type.

Pretty handy to write your own types and transpilers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM