nextjs/no-before-interactive-script-outside-document 正确性
它的作用
阻止在 pages/_document.js 之外使用 next/script 的 beforeInteractive 策略。 此规则确保使用 beforeInteractive 加载策略的脚本仅在其最有效的文档组件中使用。
这为什么不好?
beforeInteractive 策略专为在任何页面 hydration 发生之前加载脚本而设计,而这只有在放置于 pages/_document.js 中时才能保证正确工作。在其他位置使用它:
- 可能无法实现预期的早期加载行为
- 可能导致脚本加载时机不一致
- 可能引发 hydration 不匹配或其他运行时问题
- 可能影响应用程序的性能优化
示例
以下是此规则的错误代码示例:
jsx
// pages/index.js
import Script from "next/script";
export default function HomePage() {
return (
<div>
<Script
src="https://example.com/script.js"
strategy="beforeInteractive" // ❌ 错误位置
/>
</div>
);
}以下是此规则的正确代码示例:
jsx
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Script
src="https://example.com/script.js"
strategy="beforeInteractive" // ✅ 正确位置
/>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["nextjs"],
"rules": {
"nextjs/no-before-interactive-script-outside-document": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["nextjs"],
rules: {
"nextjs/no-before-interactive-script-outside-document": "error",
},
});bash
oxlint --deny nextjs/no-before-interactive-script-outside-document --nextjs-plugin版本
此规则在 v0.2.7 中添加。
