【问题标题】:How can I import umd with <script type="module"> into browser including node_modules如何将带有 <script type="module"> 的 umd 导入浏览器,包括 node_modules
【发布时间】:2023-03-16 21:25:01
【问题描述】:

我可以在没有 Webpack 的情况下以某种方式转换 typescript 代码并将其导入浏览器吗?我在代码中使用了 node_modules,所以这有点复杂。

我已尝试将其作为模块导入:

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

但它只导入了这个奇怪的东西:

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

对我来说最好的选择是将其转换为 umd 以便它可以普遍导入浏览器/作为 node_module 导入。

【问题讨论】:

    标签: typescript browser node-modules es6-modules html-imports


    【解决方案1】:

    其实取决于导入文件的内容。

    例如,如果 index.js 如下:

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

    然后使用您的代码,您应该使用foo.x 访问x 值,或使用foo.y() 调用y() 函数。

    您也可以使用另一种语法只获取一个导出的对象:

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

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多