代码之家  ›  专栏  ›  技术社区  ›  1.21 gigawatts

尝试将单个TypeScript文件与Bun绑定时获取ReferenceError

bun
  •  0
  • 1.21 gigawatts  · 技术社区  · 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这将在浏览器中运行?

    如果我构建 index.ts 使用TypeScript,我不会出现任何错误。这是我的 tsconfig.json :

    {
      "compilerOptions": {
        "target": "ESNext",
        "module": "Preserve",
        "inlineSourceMap": true,
        "esModuleInterop": true,  
        "forceConsistentCasingInFileNames": true, 
    
        "strict": true,
        "noImplicitOverride": true,
        "allowUnreachableCode": true,
        "skipLibCheck": true
      }
    }
    
    

    我已经尝试将web库添加到其中,但仍然会出现错误 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 。这将指向我的配置文件。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Jared Smith    1 年前

    跑步 bun run some-file.ts 很像跑步 node some-file.js 这个 window 对象不会出现在那个里,除非您用jsdom之类的东西来伪造它。

    但bun内置了各种API,也是一种“厨房水槽”工具。你似乎想要的是 build :

    bun bun.build.js
    

    然后在你的bun.build文件中这样做

    await Bun.build({
      entrypoints: ['./index.ts'],
      outdir: './build',
    });
    

    您也可以使用 build subcommand 直接代替Javascript API:

    bun build ./index.ts --outdir ./build
    

    还要注意,您看到的关于的错误 运行时 错误它实际上和Typescript并没有任何关系:您正试图将文件作为node.js程序运行,所以窗口将是未定义的。你会看到的 ReferenceError 在严格模式下或在松散模式下“无法读取未定义的属性blah”。请记住,如果你得到了一个实际的Javascript错误,你已经通过了TS编译器:调整TS配置可能会将运行时错误变成编译时错误(例如,通过启用严格的null检查),但它本身并不能真正解决问题。

    推荐文章