Skip to content

context

  • 类型:string

    ¥Type: string

  • 可选:是 ✅

    ¥Optional: Yes ✅

每个输出块顶层 this 的值。对于 IIFE 和 UMD 格式,默认为 'window''global',具体取决于平台。

¥The value of this at the top level of each output chunk. For IIFE and UMD formats, this defaults to 'window' or 'global' depending on the platform.

示例

¥Examples

设置自定义上下文

¥Set custom context

js
export default {
  context: 'globalThis',
  output: {
    format: 'iife',
  },
};

使用窗口浏览器构建

¥Use window for browser builds

js
export default {
  context: 'window',
  platform: 'browser',
  output: {
    format: 'iife',
  },
};

深入探讨

¥In-depth

context 选项控制 this 在打包代码的顶层作用域中引用的内容。这对于以下情况尤为重要:

¥The context option controls what this refers to in the top-level scope of your bundled code. This is particularly important for:

  • 需要访问全局对象的 IIFE 包

    ¥IIFE bundles that need to access global objects

  • 可在多种环境下运行的 UMD 包

    ¥UMD bundles that run in multiple environments

  • 在顶层引用 this 的代码

    ¥Code that references this at the top level

默认:

¥By default:

  • 对于浏览器平台上的 'iife''umd' 格式:this'window'

    ¥For 'iife' and 'umd' formats on browser platform: this is 'window'

  • 对于 Node 平台上的 'iife''umd' 格式:this'global'

    ¥For 'iife' and 'umd' formats on node platform: this is 'global'

  • 对于 ES 模块:thisundefined

    ¥For ES modules: this is undefined

使用 'globalThis' 提供了一种跨平台访问全局对象的方法,该对象在浏览器和 Node.js 环境中均可使用。

¥Using 'globalThis' provides a cross-platform way to access the global object that works in both browser and Node.js environments.