Getting "Uncaught ReferenceError: x is not defined" How to reference data from a typescript bundled js file from another script?

Getting "Uncaught ReferenceError: x is not defined" How to reference data from a typescript bundled js file from another script?

我正在为打字稿做一些测试设置。我的主要重点是将所有 .ts 模块捆绑到一个 .js 文件中,该文件可以在一个简单的 index.html 中被客户端引用。这是我的测试模块:

// index.ts
import { Example } from './example'

class x {
  example(): void {
    console.log(Example)
  }
}

let test = new x()
test.example()

// example.ts
export const Example : string = 'Example Message'

我使用 Webpack 5 和 ts-loader 将所有内容编译成 bundle.js 文件。然后,我创建了一个 .html 文件来测试创建的 class。 index.ts 中的 test.example()(然后是 bundle.js)正确执行,但是 <script/> 中的第二个报告 Uncaught ReferenceError: x is not defined.

<!-- index.html -->
<html>
  <script src="../dist/js/bundle.js"></script>
  <script>
    // Uncaught ReferenceError: x is not defined
    let test = new x()
    test.example()
  </script>
</html>

如何从第二个 <script/> 中引用我的 class x?

How can I reference my class x from the second <script/>?

你不能。至少在不修改源代码结构的情况下不会。

捆绑器将所有可执行代码放入捆绑包中。这包括您的依赖项和您的应用程序代码。所有这些都只是真正设计用于通过 importexport 关键字在该捆绑包中工作。

捆绑器以不污染全局范围的方式管理这些 import/exports。但它确实要求您留在该捆绑包内。

但是,您似乎希望您的包在该全局范围内提供一些值。为此,您必须明确说明。

class x {
  example(): void {
    console.log(Example)
  }
}

// Add `x` to the browser's global scope.
window.x = x

现在,来自其他 <script> 标签 new x() 应该可以如您所愿地工作。