Can I import ES Modules from other <script type="module">

Viewed 242

I want to import from another script tag.

<script type="module">
    export default "str"
</script>

<script type="module">
    import foo from "????"
    console.log(foo) // str
</script>

What should I write in "???"?

1 Answers

It's not possible. A ModuleSpecifier (what comes after the from) must be a string, and needs to point to a standalone JavaScript file with exports. It can't reference another script tag on the page, only a file.

Usually, a <script type="module"> on the page itself is only used once, and is used to call other modules. For example, rather than your original code, you'd usually see or have something like:

<script type="module">
    import foo from "str.js"
    console.log(foo) // str
</script>
// str.js
export default "str"
Related