Search code examples
typescriptbrowsernode-moduleses6-moduleshtml-imports

How can I import umd with <script type="module"> into browser including node_modules


Can I somehow transpile typescript code and import it into the browser without Webpack? I am using node_modules in the code so this is making it a bit complicated.

I have tried to import it as a module:

<script type="module">
   import * as foo from '../../dist/index.js';
   console.log(foo);
</script>

But it imported only this strange thing:

Module {Symbol(Symbol.toStringTag): "Module"}

The best option for me would be to transpile it as umd so it can be universally imported into the browser / imported as a node_module.


Solution

  • Actually it depends on the content of imported file.

    For example, if index.js is like below:

    export const x = "Hello World"
    export function y() { console.log( "y()" ) }
    

    Then with your code you should use foo.x to access the x value, or foo.y() to invoke the y() function.

    You could also get only one exported object by using another syntax:

    <script type="module">
       import {x} from '../../dist/index.js';
       console.log(x);
    </script>