我一直在试验最近添加到浏览器的新的原生 ECMAScript module支持。终于能够直接、干净地从 JavaScript 导入脚本是一件令人愉快的事情。
/example.html 🔍
<script type="module">
import {example} from '/example.js';
example();
</script>
/example.js
export function example() {
document.body.appendChild(document.createTextNode("hello"));
};
但是,这只允许我导入由单独的外部JavaScript 文件定义的module。我通常更喜欢内联一些用于初始渲染的脚本,因此它们的请求不会阻塞页面的其余部分。对于传统的非正式结构的库,它可能如下所示:
/inline-traditional.html 🔍
<body>
<script>
var example = {};
example.example = function() {
document.body.appendChild(document.createTextNode("hello"));
};
</script>
<script>
example.example();
</script>
但是,天真地内联module文件显然是行不通的,因为它会删除用于将module标识为其他module的文件名。HTTP/2 服务器推送可能是处理这种情况的规范方式,但它仍然不是所有环境中的一种选择。
是否可以使用 ECMAScript module执行等效转换?
a 有什么办法可以<script type="module">
在同一个文档中导入另一个导出的module?
我想这可以通过允许脚本指定文件路径来工作,并且表现得好像它已经从路径下载或推送一样。
/inline-name.html 🔍
<script type="module" name="/example.js">
export function example() {
document.body.appendChild(document.createTextNode("hello"));
};
</script>
<script type="module">
import {example} from '/example.js';
example();
</script>
或者可能使用完全不同的参考方案,例如用于本地 SVG 参考:
/inline-id.html 🔍
<script type="module" id="example">
export function example() {
document.body.appendChild(document.createTextNode("hello"));
};
</script>
<script type="module">
import {example} from '#example';
example();
</script>
但是这些假设都没有实际工作,而且我还没有看到替代方案。