Search code examples
javascripthtmles6-modules

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


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 "???"?


Solution

  • 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"