How to transpile index.html with babel?

2019-07-29 17:17发布

问题:

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.

回答1:

You can't.

Babel is a JavaScript transpiler, it doesn't deal with HTML, or even JavaScript embedded in HTML.

Rewrite your HTML to use external JavaScript. Use addEventListener instead of intrinsic event handler attributes. Then apply Babel to the JS files.



标签: html babeljs