尝试将单个 TypeScript 文件与 Bun 捆绑在一起时出现 ReferenceError

问题描述 投票:0回答:1

当我运行

bun run index.ts
时,我收到错误:

npm run start
Debugger attached.

> [email protected] start
> bun run index.ts

11 |     dialogCallback;
12 |     static PAGE_LOADED = "DOMContentLoaded";
13 |     constructor() {
14 |     }
15 |     static startWhenReady(ClassReference, startWith) {
16 |         window.addEventListener(BaseClass.PAGE_LOADED, (event) => {       
             ^
ReferenceError: Can't find variable: window
      at startWhenReady (BaseClass.js:16:9)
      at index.ts:12:11

我需要进口一些东西吗?或者以某种方式告诉 Bun 这将在浏览器中运行?

如果我使用 TypeScript 构建

index.ts
,我不会收到任何错误。这是我的
tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "Preserve",
    "inlineSourceMap": true,
    "esModuleInterop": true,  
    "forceConsistentCasingInFileNames": true, 

    "strict": true,
    "noImplicitOverride": true,
    "allowUnreachableCode": true,
    "skipLibCheck": true
  }
}

我已经尝试向其中添加网络库,但仍然遇到错误

bun run index.ts

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "Preserve",
    "inlineSourceMap": true,
    "esModuleInterop": true,  
    "forceConsistentCasingInFileNames": true, 
    "lib": ["es2022", "dom", "dom.iterable"],

    /* Type Checking */
    "strict": true,
    "noImplicitOverride": true,
    "allowUnreachableCode": true,
    "skipLibCheck": true
  }
}

index.ts

import {BaseClass} from "base-class-ts/BaseClass"


export class MyClass extends BaseClass {

    constructor() {
        super();
        console.log("Hello world ...") 
    }
}

BaseClass.startWhenReady(MyClass);

我一直在打电话给

bun run start
,现在我认为应该是,
bun bun.build.js
。这将指向我的配置文件。

bun
1个回答
0
投票

跑步

bun some-file.ts
很像跑步
node some-file.js
。 Bun 还内置了各种 API,成为“厨房水槽”工具。您似乎想要的是
build
:

bun bun.build.js

另请注意,您看到的错误是“运行时”错误。它实际上与 Typescript 没有任何关系:您正在尝试将文件作为 node.js 程序运行,因此 window 将是未定义的。您会在严格模式下看到 ReferenceError 或在松散模式下看到“无法读取未定义的属性”。请记住,如果您收到实际的 Javascript 错误,那么您已经通过了 TS 编译器。

    

© www.soinside.com 2019 - 2024. All rights reserved.