no-before-interactive-script-outside-document.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const path = require('path')
  2. const url =
  3. 'https://nextjs.org/docs/messages/no-before-interactive-script-outside-document'
  4. module.exports = {
  5. meta: {
  6. docs: {
  7. description:
  8. "Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `pages/_document.js`.",
  9. recommended: true,
  10. url,
  11. },
  12. type: 'problem',
  13. schema: [],
  14. },
  15. create: function (context) {
  16. let scriptImportName = null
  17. return {
  18. 'ImportDeclaration[source.value="next/script"] > ImportDefaultSpecifier'(
  19. node
  20. ) {
  21. scriptImportName = node.local.name
  22. },
  23. JSXOpeningElement(node) {
  24. if (!scriptImportName) {
  25. return
  26. }
  27. if (node.name && node.name.name !== scriptImportName) {
  28. return
  29. }
  30. const strategy = node.attributes.find(
  31. (child) => child.name && child.name.name === 'strategy'
  32. )
  33. if (
  34. !strategy ||
  35. !strategy.value ||
  36. strategy.value.value !== 'beforeInteractive'
  37. ) {
  38. return
  39. }
  40. const document = context.getFilename().split('pages')[1]
  41. if (document && path.parse(document).name.startsWith('_document')) {
  42. return
  43. }
  44. context.report({
  45. node,
  46. message: `\`next/script\`'s \`beforeInteractive\` strategy should not be used outside of \`pages/_document.js\`. See: ${url}`,
  47. })
  48. },
  49. }
  50. },
  51. }