You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Miniflare的Cloudflare Workers全局变量/函数访问异常问题

问题描述

我在使用Cloudflare Workers结合Miniflare开发时遇到两个相关问题:

  1. 最初在bindings.d.ts中全局声明函数getMiniflareBindings(),但运行时抛出ReferenceError: getMiniflareBindings is not defined错误。
  2. 改为在bindings.d.ts中全局声明常量后,生产和开发环境能正常访问这些变量,但测试环境中所有变量均显示“未定义”。

附上当前配置文件:

build.js

import { build } from 'esbuild'

try {
  await build({
      entryPoints: ['./src/index.ts'],
      bundle: true,
      outdir: './dist/',
      sourcemap: true,
      minify: true
    })
} catch(err) {
  process.exitCode = 1;
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "target": "esnext",
    "lib": ["esnext"],
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "inlineSourceMap": true,
    "module": "esnext",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true,
    "noImplicitAny": true,
    "noEmit": true,
    "types": [
      "@cloudflare/workers-types",
      "@types/bcryptjs"
    ]
  },
  "ts-node": {
    "transpileOnly": true
  },
  "include": ["./src/**/*", "bindings.d.ts"]
}
排查与解决方案

关于getMiniflareBindings()未定义的问题

  • getMiniflareBindings()是Miniflare专为测试场景提供的函数,只能在测试用例中(比如Jest/Vitest配合Miniflare初始化后)调用,Worker运行时(包括Miniflare开发服务器)不会自动注入这个函数。
  • Worker业务代码应直接通过全局变量访问绑定,该函数仅用于测试代码中获取绑定实例。

关于测试环境全局绑定未定义的问题

1. 确保测试环境正确初始化Miniflare并注入绑定

测试时需显式创建Miniflare实例并配置绑定,而非依赖全局自动注入。示例(以Vitest为例):

import { Miniflare } from 'miniflare';

describe('Worker测试', () => {
  let mf: Miniflare;

  beforeAll(async () => {
    mf = new Miniflare({
      scriptPath: './dist/index.js',
      bindings: {
        // 配置你的绑定变量、KV命名空间等
        MY_VAR: 'test_value',
        MY_KV: { type: 'kv', id: 'test-kv' }
      },
      modules: true, // 若Worker使用ES模块语法需开启
    });
  });

  test('测试绑定访问', async () => {
    const bindings = await mf.getBindings();
    // 通过bindings对象访问变量,而非直接全局调用
    expect(bindings.MY_VAR).toBe('test_value');
  });
});

2. 修正bindings.d.ts类型声明

确保类型声明覆盖全局范围,同时适配测试场景:

// bindings.d.ts
declare global {
  // Worker运行时的全局绑定类型定义
  const MY_VAR: string;
  const MY_KV: KVNamespace;

  // 仅在测试环境中声明getMiniflareBindings类型
  function getMiniflareBindings(): Promise<{
    MY_VAR: string;
    MY_KV: KVNamespace;
  }>;
}

export {};

3. 检查ESBuild配置对绑定的影响

  • 你的ESBuild开启了bundle: true和minify: true,若Worker代码中未显式使用绑定变量,minify阶段可能会将其优化删除。测试时可临时关闭minify: true排查是否为此原因。
  • 确认Miniflare的scriptPath指向正确的打包产物路径./dist/index.js。

4. 优化测试环境TypeScript配置

若测试用例使用TS编写,建议单独创建测试用tsconfig(如tsconfig.test.json),确保包含Miniflare类型支持:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "types": ["@cloudflare/workers-types", "@types/bcryptjs", "@miniflare/core"]
  },
  "include": ["./src/**/*", "./test/**/*", "bindings.d.ts"]
}

内容的提问来源于stack exchange,提问作者OultimoCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:35:19