Search code examples
javascriptwebpackecmascript-6babeljstranspiler

How to transpile a script tag within an HTML document during a webpack build?


Note: I am aware of https://github.com/babel/babel-standalone#usage and am not asking about transpiling in the browser.

I'm wondering if either of the following is possible:

Option 1 - Transpile stuff in an HTML file

Say I have the following src/index.html with some inline ES6:

<!-- src/index.html -->
<h1>This is some HTML stuff...</h1>
<script>
     () => console.log('I am some inline JS.');
</script>

After some type of build end up with the following dist/index.html which has inline ES5:

<!-- dist/index.html -->
<h1>This is some HTML stuff...</h1>
<script>
    function() {
        console.log('I am some inline JS.');
    }
</script>

Option 2 - Concatenate transpiled JS to an HTML file

Say I have the following src files:

<!-- src/index.html -->
<h1>This is some HTML stuff...</h1>

and a JS which contains ES6:

// src/index.js
() => console.log('I am some JS from another file.');

After some type of build end up with the following dist/index.html which has inline ES5 concatenated to the bottom of the file in a script tag:

<!-- dist/index.html -->
<h1>This is some HTML stuff...</h1>
<script>
    function() {
        console.log('I am some JS from another file.');
    }
</script>

I've looked through a bunch of webpack loaders, but nothing seems to fit this. There may be a really simple solution, but what am I missing? Is there a babel plugin or webpack loader which could handle either of these.

P.S. I would prefer a setup with Option 1.


Solution

  • The Polymer team has a util that strips js from html. Crisper. You can use that to strip the js from the script tags, then feed it to your transpiler, then inject it back into the html.