Unverified Commit 8ae12db1 authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

ESLint Plugin: Fix Document and Head import rules (#25730)

parent 58796411
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
### Why This Error Occurred ### Why This Error Occurred
`next/document` was imported in a page outside of `pages/_document.js`. This can cause unexpected issues in your application. `next/document` was imported in a page outside of `pages/_document.js` (or `pages/_document.tsx` if you are using TypeScript). This can cause unexpected issues in your application.
### Possible Ways to Fix It ### Possible Ways to Fix It
Only import and use `next/document` within `pages/_document.js` to override the default `Document` component: Only import and use `next/document` within `pages/_document.js` (or `pages/_document.tsx`) to override the default `Document` component:
```jsx ```jsx
// pages/_document.js // pages/_document.js
......
...@@ -16,7 +16,7 @@ module.exports = { ...@@ -16,7 +16,7 @@ module.exports = {
} }
const page = context.getFilename().split('pages')[1] const page = context.getFilename().split('pages')[1]
if (!page || path.parse(page).name === '_document') { if (!page || path.parse(page).name.startsWith('_document')) {
return return
} }
......
...@@ -15,7 +15,7 @@ module.exports = { ...@@ -15,7 +15,7 @@ module.exports = {
} }
const document = context.getFilename().split('pages')[1] const document = context.getFilename().split('pages')[1]
if (!document || path.parse(document).name !== '_document') { if (!document || !path.parse(document).name.startsWith('_document')) {
return return
} }
......
...@@ -44,6 +44,20 @@ ruleTester.run('no-document-import-in-page', rule, { ...@@ -44,6 +44,20 @@ ruleTester.run('no-document-import-in-page', rule, {
`, `,
filename: 'pages/_document.tsx', filename: 'pages/_document.tsx',
}, },
{
code: `import Document from "next/document"
export default class MyDocument extends Document {
render() {
return (
<Html>
</Html>
);
}
}
`,
filename: 'pages/_document.page.tsx',
},
], ],
invalid: [ invalid: [
{ {
......
...@@ -84,5 +84,35 @@ ruleTester.run('no-head-import-in-document', rule, { ...@@ -84,5 +84,35 @@ ruleTester.run('no-head-import-in-document', rule, {
}, },
], ],
}, },
{
code: `
import Document, { Html, Main, NextScript } from 'next/document'
import Head from 'next/head'
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
`,
filename: 'pages/_document.page.tsx',
errors: [
{
message:
'next/head should not be imported in pages/_document.page.tsx. Import Head from next/document instead. See https://nextjs.org/docs/messages/no-head-import-in-document.',
type: 'ImportDeclaration',
},
],
},
], ],
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment