no-title-in-document-head.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const url = 'https://nextjs.org/docs/messages/no-title-in-document-head'
  2. module.exports = {
  3. meta: {
  4. docs: {
  5. description:
  6. 'Prevent usage of `<title>` with `Head` component from `next/document`.',
  7. recommended: true,
  8. url,
  9. },
  10. type: 'problem',
  11. schema: [],
  12. },
  13. create: function (context) {
  14. let headFromNextDocument = false
  15. return {
  16. ImportDeclaration(node) {
  17. if (node.source.value === 'next/document') {
  18. if (node.specifiers.some(({ local }) => local.name === 'Head')) {
  19. headFromNextDocument = true
  20. }
  21. }
  22. },
  23. JSXElement(node) {
  24. if (!headFromNextDocument) {
  25. return
  26. }
  27. if (
  28. node.openingElement &&
  29. node.openingElement.name &&
  30. node.openingElement.name.name !== 'Head'
  31. ) {
  32. return
  33. }
  34. const titleTag = node.children.find(
  35. (child) =>
  36. child.openingElement &&
  37. child.openingElement.name &&
  38. child.openingElement.name.type === 'JSXIdentifier' &&
  39. child.openingElement.name.name === 'title'
  40. )
  41. if (titleTag) {
  42. context.report({
  43. node: titleTag,
  44. message: `Do not use \`<title>\` element with \`<Head />\` component from \`next/document\`. Titles should defined at the page-level using \`<Head />\` from \`next/head\` instead. See: ${url}`,
  45. })
  46. }
  47. },
  48. }
  49. },
  50. }