no-cjs-in-config.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @fileoverview Disallow `require/modules.exports/exports` in `nuxt.config.js`
  3. * @author Xin Du <clark.duxin@gmail.com>
  4. */
  5. 'use strict'
  6. const path = require('path')
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description:
  14. 'disallow commonjs module api `require/modules.exports/exports` in `nuxt.config.js`',
  15. category: 'base'
  16. },
  17. messages: {
  18. noCjs: 'Unexpected {{cjs}}, please use {{esm}} instead.'
  19. }
  20. },
  21. create (context) {
  22. // variables should be defined here
  23. const options = context.options[0] || {}
  24. const configFile = options.file || 'nuxt.config.js'
  25. let isNuxtConfig = false
  26. // ----------------------------------------------------------------------
  27. // Public
  28. // ----------------------------------------------------------------------
  29. return {
  30. Program (node) {
  31. const filename = path.basename(context.getFilename())
  32. if (filename === configFile) {
  33. isNuxtConfig = true
  34. }
  35. },
  36. MemberExpression: function (node) {
  37. if (!isNuxtConfig) {
  38. return
  39. }
  40. // module.exports
  41. if (node.object.name === 'module' && node.property.name === 'exports') {
  42. context.report({
  43. node,
  44. messageId: 'noCjs',
  45. data: {
  46. cjs: 'module.exports',
  47. esm: 'export default'
  48. }
  49. })
  50. }
  51. // exports.
  52. if (node.object.name === 'exports') {
  53. const isInScope = context.getScope()
  54. .variables
  55. .some(variable => variable.name === 'exports')
  56. if (!isInScope) {
  57. context.report({
  58. node,
  59. messageId: 'noCjs',
  60. data: {
  61. cjs: 'exports',
  62. esm: 'export default'
  63. }
  64. })
  65. }
  66. }
  67. },
  68. CallExpression: function (call) {
  69. const module = call.arguments[0]
  70. if (
  71. !isNuxtConfig ||
  72. context.getScope().type !== 'module' ||
  73. !['ExpressionStatement', 'VariableDeclarator'].includes(call.parent.type) ||
  74. call.callee.type !== 'Identifier' ||
  75. call.callee.name !== 'require' ||
  76. call.arguments.length !== 1 ||
  77. module.type !== 'Literal' ||
  78. typeof module.value !== 'string'
  79. ) {
  80. return
  81. }
  82. context.report({
  83. node: call.callee,
  84. messageId: 'noCjs',
  85. data: {
  86. cjs: 'require',
  87. esm: 'import'
  88. }
  89. })
  90. }
  91. }
  92. }
  93. }