I read the W3schools tutorial and have some questions regarding how how a browser transpiled the html file.
example.html
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin</script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="mydiv"></div>
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
ReactDOM.render(<Hello/>, document.getElementById('mydiv'))
</script>
</body>
When I do inspect in chome, I saw this:
<html>
<head>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin=""></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin=""></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script>"use strict";
function Hello() {
return /*#__PURE__*/React.createElement("h1", null, "Hello World!");
}
ReactDOM.render( /*#__PURE__*/React.createElement(Hello, null), document.getElementById('mydiv'));
</script>
</head>
<body>
<div id="mydiv">
<h1>Hello World!</h1>
</div>
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
ReactDOM.render(<Hello />, document.getElementById('mydiv'))
</script>
</body>
A few questions:
babel.min.js
sets up a listener, which upon script loading completion, picked out the <script type="text/babel">
part and translated it into a legit js, and stuck it under <head>
section?<script type="text/babel">
is left inplace and it wouldn't be run by browser anymore? why?Answering your questions one by one...
type="text/javascript"
gets automatically executed by the browser, otherwise it'll be left alone. If it's an external script with an unrecognized type, the browser won't load it either. Babel queries all your Babel scripts from the document (e.g. document.querySelectorAll('[type="text/babel"]')
), and if they're inline, Babel transpiles them, then sticks the real Javascript in the HTML head, otherwise Babel sends an AJAX request, them does its magic.So there you have it. Be advised though, this is the least ideal way to use Babel, and you definitely shouldn't use this in production (you should pretranspile it).