no-env-in-hooks.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @fileoverview disallow process.server, process.client and process.browser in the following lifecycle hooks: beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy and destroyed
  3. * @author Xin Du <clark.duxin@gmail.com>
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description:
  14. 'disallow process.server and process.client in the following lifecycle hooks: beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy and destroyed',
  15. category: 'base'
  16. },
  17. messages: {
  18. noEnv: 'Unexpected {{name}} in {{funcName}}.'
  19. }
  20. },
  21. create (context) {
  22. // variables should be defined here
  23. const forbiddenNodes = []
  24. const options = context.options[0] || {}
  25. const ENV = ['server', 'client', 'browser']
  26. const HOOKS = new Set(['beforeMount', 'mounted', 'beforeUpdate', 'updated', 'activated', 'deactivated', 'beforeDestroy', 'destroyed'].concat(options.methods || []))
  27. // ----------------------------------------------------------------------
  28. // Public
  29. // ----------------------------------------------------------------------
  30. return {
  31. MemberExpression (node) {
  32. const objectName = node.object.name
  33. if (objectName === 'process') {
  34. const propertyName = node.computed ? node.property.value : node.property.name
  35. if (propertyName && ENV.includes(propertyName)) {
  36. forbiddenNodes.push({ name: 'process.' + propertyName, node })
  37. }
  38. }
  39. },
  40. ...utils.executeOnVue(context, obj => {
  41. for (const funcName of HOOKS) {
  42. const func = utils.getFunctionWithName(obj, funcName)
  43. if (func) {
  44. for (const { name, node: child } of forbiddenNodes) {
  45. if (utils.isInFunction(func, child)) {
  46. context.report({
  47. node: child,
  48. messageId: 'noEnv',
  49. data: {
  50. name,
  51. funcName
  52. }
  53. })
  54. }
  55. }
  56. }
  57. }
  58. })
  59. }
  60. }
  61. }