简体   繁体   English

浏览器如何选择脚本的转译语言

[英]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最近我一直在使用将 babel 作为脚本导入的代码

<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.然后在下面的脚本中使用类型text/babel来编写 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.我想知道决定使用先前导入的 babel 来转换代码的浏览器如何识别该类型。

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.我一直假设浏览器有一组默认的脚本类型,它知道如何处理—— 而且确实如此——但text/babel显然不是其中之一。

So how does this work?那么这是如何工作的呢?

I just looked inside the babel.js file and it became obvious.我只是查看了 babel.js 文件,它变得很明显。

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. babel 脚本在text/babel脚本之前运行,它会找到所有text/babel脚本,转换并运行它们。 So the browser doesn't need to be aware of that type.所以浏览器不需要知道那个类型。

Pretty handy to write your own types and transpilers编写自己的类型和转译器非常方便

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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