no-globals-in-created.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * @fileoverview disallow `window/document` in `created/beforeCreate`
  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: 'disallow `window/document` in `created/beforeCreate`',
  14. category: 'base'
  15. },
  16. messages: {
  17. noGlobals: 'Unexpected {{name}} in {{funcName}}.'
  18. }
  19. },
  20. create (context) {
  21. const forbiddenNodes = []
  22. const options = context.options[0] || {}
  23. const HOOKS = new Set(
  24. ['created', 'beforeCreate'].concat(options.methods || [])
  25. )
  26. const GLOBALS = ['window', 'document']
  27. function isGlobals (name) {
  28. return GLOBALS.includes(name)
  29. }
  30. return {
  31. MemberExpression (node) {
  32. if (!node.object) return
  33. const name = node.object.name
  34. if (isGlobals(name)) {
  35. forbiddenNodes.push({ name, node })
  36. }
  37. },
  38. VariableDeclarator (node) {
  39. if (!node.init) return
  40. const name = node.init.name
  41. if (isGlobals(name)) {
  42. forbiddenNodes.push({ name, node })
  43. }
  44. },
  45. ...utils.executeOnVue(context, obj => {
  46. for (const { funcName, name, node } of utils.getFunctionWithChild(obj, HOOKS, forbiddenNodes)) {
  47. context.report({
  48. node,
  49. messageId: 'noGlobals',
  50. data: {
  51. name,
  52. funcName
  53. }
  54. })
  55. }
  56. })
  57. }
  58. }
  59. }