no-script-component-in-head.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const url = 'https://nextjs.org/docs/messages/no-script-component-in-head'
  2. module.exports = {
  3. meta: {
  4. docs: {
  5. description: 'Prevent usage of `next/script` in `next/head` component.',
  6. recommended: true,
  7. url,
  8. },
  9. type: 'problem',
  10. schema: [],
  11. },
  12. create: function (context) {
  13. let isNextHead = null
  14. return {
  15. ImportDeclaration(node) {
  16. if (node.source.value === 'next/head') {
  17. isNextHead = node.source.value
  18. }
  19. if (node.source.value !== 'next/script') {
  20. return
  21. }
  22. },
  23. JSXElement(node) {
  24. if (!isNextHead) {
  25. return
  26. }
  27. if (
  28. node.openingElement &&
  29. node.openingElement.name &&
  30. node.openingElement.name.name !== 'Head'
  31. ) {
  32. return
  33. }
  34. const scriptTag = node.children.find(
  35. (child) =>
  36. child.openingElement &&
  37. child.openingElement.name &&
  38. child.openingElement.name.name === 'Script'
  39. )
  40. if (scriptTag) {
  41. context.report({
  42. node,
  43. message: `\`next/script\` should not be used in \`next/head\` component. Move \`<Script />\` outside of \`<Head>\` instead. See: ${url}`,
  44. })
  45. }
  46. },
  47. }
  48. },
  49. }