【问题标题】:How to transpile a script tag within an HTML document during a webpack build?如何在 webpack 构建过程中转译 HTML 文档中的脚本标签?
【发布时间】:2018-01-15 05:23:16
【问题描述】:

注意:我知道https://github.com/babel/babel-standalone#usage,并不是询问在浏览器中的转译。

我想知道是否任一以下是可能的:

选项 1 - 在 HTML 文件中转换内容

假设我有以下 src/index.html 和一些内联 ES6:

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

经过某种类型的构建后,会得到以下具有内联 ES5 的 dist/index.html

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

选项 2 - 将转译后的 JS 连接到 HTML 文件

假设我有以下src 文件:

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

还有一个包含 ES6 的 JS:

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

在某种类型的构建之后,会得到以下dist/index.html,它在script 标记中将内联ES5 连接到文件底部:

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

我浏览了一堆 webpack 加载器,但似乎没有一个适合这个。可能有一个非常简单的解决方案,但我错过了什么?是否有可以处理其中任何一个的 babel 插件或 webpack 加载器。

附:我更喜欢选项 1 的设置。

【问题讨论】:

  • 选项 3:编写在预期使用的环境中工作的代码!
  • :) 谢谢。我应该提一下,我会支持 IE11 现代浏览器。我想用 ES6 编写,但会根据客户端提供不同版本的最终 HTML。

标签: javascript webpack ecmascript-6 babeljs transpiler


【解决方案1】:

Polymer 团队有一个工具可以从 html 中剥离 js。 Crisper。您可以使用它从脚本标签中剥离 js,然后将其提供给您的转译器,然后将其注入回 html。

【讨论】:

  • 这很有趣。谢谢!
猜你喜欢
  • 2021-03-04
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多