rsnext/packages/eslint-plugin-next/lib/rules/no-server-import-in-page.js
Thibaut SABOT 5b4e139dde
Fix no-server-import-in-page eslint rule for subfolder middleware (#32139)
People have been reporting on https://github.com/vercel/next.js/pull/30973 that the `no-server-import-in-page` eslint rule is reporting false positives for `_middleware` files inside sub-page folders.

Unlike `_document`, we can have multiple `_middleware` files.

Fixes #32121
2021-12-05 14:41:10 +00:00

37 lines
941 B
JavaScript

const path = require('path')
module.exports = {
meta: {
docs: {
description:
'Disallow importing next/server outside of pages/_middleware.js',
recommended: true,
url: 'https://nextjs.org/docs/messages/no-server-import-in-page',
},
},
create: function (context) {
return {
ImportDeclaration(node) {
if (node.source.value !== 'next/server') {
return
}
const paths = context.getFilename().split('pages')
const page = paths[paths.length - 1]
if (
!page ||
page.includes(`${path.sep}_middleware`) ||
page.includes(`${path.posix.sep}_middleware`)
) {
return
}
context.report({
node,
message: `next/server should not be imported outside of pages/_middleware.js. See https://nextjs.org/docs/messages/no-server-import-in-page.`,
})
},
}
},
}