azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.84k stars 260 forks source link

【每日一题】- 2020-01-14 - @babel/standalone 的原理是什么? #95

Closed azl397985856 closed 4 years ago

azl397985856 commented 4 years ago

比如:

<div id="output"></div>
<!-- Load Babel -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>

我们可以使用如上代码,使得不支持const的浏览器能够运行,即会修改id为output的元素(如果存在的话)innerHTML为"Hello World"

请问这是怎么实现的?

feikerwu commented 4 years ago

@babel/standalone 在html文档被解析完,即DOMContentLoaded事件触发时,获取html文档中带有特殊标记,比如 text/babel 的script标签里面的内容,获取到content之后,传给babel编译,得到低版本浏览器可以支持的代码文本,然后新建一个script标签,将编译后的文本代码塞进去,将script插回到html,然后就可以运行了