I've been experimenting with new native ECMAScript module support that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript.
??? ?/example.html ???
???
<script type="module">
import {example} from '/example.js';
example();
</script>
??? ?/example.js?
???
export function example() {
document.body.appendChild(document.createTextNode("hello"));
};
However, this only allows me to import modules that are defined by separate external JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this:
??? ?/inline-traditional.html ???
???
<body>
<script>
var example = {};
example.example = function() {
document.body.appendChild(document.createTextNode("hello"));
};
</script>
<script>
example.example();
</script>
However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments.
Is it possible to perform an equivalent transformation with ECMAScript modules?
Is there any way for a <script type="module">
to import a module exported by another in the same document?
I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path.
??? ?/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>
Or maybe by an entirely different reference scheme, such as is used for local SVG references:
??? ?/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>
But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…