htmlbabeljs

How to transpile index.html with babel?


I have a webpage with ES6 modules that I want to transpile with babel to ES5. Following the babel documentation on https://babeljs.io/docs/setup/#installation, I can successfully transpile the javascript folder with ./node_modules/.bin/babel js -d target but they don't transpile any HTML there. How can I transpile my index.html? Using it with the same syntax fails:

./node_modules/.bin/babel index.html -d index2.html
SyntaxError: index.html: Unexpected token (1:0)
> 1 | <!DOCTYPE html>
    | ^
  2 | <html>
  3 | 
  4 | <head>

MWE

export default "Hello World";
    <!DOCTYPE html>
    <html>
    <body>
    <script type="module">
    import message from "./js/message.js";
    window.message = message;
    </script>
    <button onclick="alert(`Message: ${window.message}`);">Get Message</button>
    </body>
    </html>

I'm using babel 6.24.1 (babel-core 6.25.0) with npm 3.10.10. I know I don't need modules for this MWE, the real page is much more complex.

P.S.: I want to continue developing the untranspiled version to preserve my workflow. I want to use the transpiled code only for production.


Solution

  • As of 2025, this is now possible with Babel Standalone 1. Here is an example from their documentation:

    <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>