禁止 window 前缀
注意:此规则是
recommended 规则集的一部分。在
deno.json 中启用完整集合{
"lint": {
"rules": {
"tags": ["recommended"]
}
}
}使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
通过将其添加到
deno.json 中的 include 或 exclude 数组中,可以将此规则显式地包含或排除在当前标签中存在的规则之外。{
"lint": {
"rules": {
"include": ["no-window-prefix"],
"exclude": ["no-window-prefix"]
}
}
}禁止通过 window 对象使用 Web API。
在大多数情况下,全局变量 window 的作用与 globalThis 类似。例如,你可以像 window.fetch(..) 那样调用 fetch API,而不是 fetch(..) 或 globalThis.fetch(..)。然而,在 Web Workers 中,window 不可用,但 self、globalThis 或无前缀的调用均可正常工作。因此,为了 Web Workers 和其他上下文之间的兼容性,强烈建议不要通过 window 访问全局属性。
某些 API,包括 window.alert、window.location 和 window.history,允许使用 window 调用,因为这些 API 在 Workers 中不受支持或具有不同的含义。换句话说,此 lint 规则仅在 window 可以完全被 self、globalThis 或无前缀替代的情况下,才会对使用 window 的情况发出警告。
无效示例
const a = await window.fetch("https://deno.land");
const b = window.Deno.metrics();
有效示例
const a1 = await fetch("https://deno.land");
const a2 = await globalThis.fetch("https://deno.land");
const a3 = await self.fetch("https://deno.land");
const b1 = Deno.metrics();
const b2 = globalThis.Deno.metrics();
const b3 = self.Deno.metrics();
// `alert` is allowed to call with `window` because it's not supported in Workers
window.alert("🍣");
// `location` is also allowed
window.location.host;