Skip to content

Commit

Permalink
handle edge case for no-import-document rule (#28261)
Browse files Browse the repository at this point in the history
Co-authored-by: JJ Kasper <jj@jjsweb.site>
  • Loading branch information
housseindjirdeh and ijjk committed Aug 25, 2021
1 parent 220fa9c commit 9442925
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 16 deletions.
@@ -1,5 +1,3 @@
const path = require('path')

module.exports = {
meta: {
docs: {
Expand All @@ -15,15 +13,10 @@ module.exports = {
return
}

const page = context.getFilename().split('pages')[1]
if (!page) {
return
}
const { name, dir } = path.parse(page)
if (
name.startsWith('_document') ||
(dir === '/_document' && name === 'index')
) {
const paths = context.getFilename().split('pages')
const page = paths[paths.length - 1]

if (!page || page.startsWith('/_document')) {
return
}

Expand Down
29 changes: 24 additions & 5 deletions test/unit/eslint-plugin-next/no-document-import-in-page.test.ts
Expand Up @@ -84,21 +84,40 @@ ruleTester.run('no-document-import-in-page', rule, {
`,
filename: 'pages/_document/index.tsx',
},
{
code: `import Document from "next/document"
export default class MyDocument extends Document {
render() {
return (
<Html>
</Html>
);
}
}
`,
filename: 'pagesapp/src/pages/_document.js',
},
],
invalid: [
{
code: `import Document from "next/document"
export const Test = () => <p>Test</p>
`,
filename: 'components/test.js',
errors: [
{
message:
'next/document should not be imported outside of pages/_document.js. See https://nextjs.org/docs/messages/no-document-import-in-page.',
type: 'ImportDeclaration',
},
],
},
],
invalid: [
{
code: `import Document from "next/document"
export const Test = () => (
<p>Test</p>
)
export const Test = () => <p>Test</p>
`,
filename: 'pages/test.js',
errors: [
Expand Down

0 comments on commit 9442925

Please sign in to comment.