babel/babel-standalone

Change `type` attribute to other to use with native esm type="module"

mizchi opened this issue · 7 comments

Native es modules needs type='module' to compile. babel-standalone need this field so I can't use both.

In Chrome Canary (64)

<script type="module">
import xxx from '/deps/xxx.js';
</script>

I'm not quite sure how you'd use both together... Can you elaborate on how it'd work? I don't know a lot about ES modules.

My use case is as follows: a react-based library uses ES6 export. Therefore it has to be imported within a <script type="module">. Then that script needs to use Babel to make use of the components defined in the library.

But the script cannot have both type= "module" and type="text/babel".

The workaround I found is to use another script, and to pass the library exports via window... According to this article the second script should be "defer" but it works without.

<script type="module" >
    import {Comp} from "./myLib.js"
    window.Comp=Comp
</script>
<script defer type="text/babel">
     ReactDOM.render(
		  <Comp/>,
		  document.getElementById('root'));
</script>
<div id="root"></div>

Actually it is also possible to skip ES6 import and parse the library with Babel so all imports and exports are transpiled (and not really used, but at least the library has the same source code in standalone mode as in node.js use)

<script>var exports = {}; var require=()=>React;</script>
<script type="text/babel"  src="./myLib.js"></script>
<script type="text/babel">
     ReactDOM.render(
		  <Comp/>,
		  document.getElementById('root'));
</script>
<div id="root"></div>

I just came across this same issue. Where I would like the contents of a <script type='module'> to be transpiled by babel standalone.

Is there a particular reason you chose to use the type attribute as a flag to indicate that the script should be transformed? Or could it have been any attribute like class or data-babel?

Humm.. then would it be possible to specify the type of the outputted script.. maybe by saying something like <script type='text/babel/module'>...</script> which outputs:

<script type='module'>${transformedCode}</script>

Also unable to use the ES6 module attribute type with text/babel in my React JSX apps. I think using a data attribute for babel may be the way to go, freeing up the type attribute for the ES6 module type.