no-multi-spaces.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @fileoverview This rule warns about the usage of extra whitespaces between attributes
  3. * @author Armano
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Rule Definition
  8. // ------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: 'disallow multiple spaces',
  13. category: 'strongly-recommended',
  14. url: 'https://github.com/vuejs/eslint-plugin-vue/blob/v4.7.1/docs/rules/no-multi-spaces.md'
  15. },
  16. fixable: 'whitespace', // or "code" or "whitespace"
  17. schema: []
  18. },
  19. /**
  20. * @param {RuleContext} context - The rule context.
  21. * @returns {Object} AST event handlers.
  22. */
  23. create (context) {
  24. // ----------------------------------------------------------------------
  25. // Public
  26. // ----------------------------------------------------------------------
  27. return {
  28. Program (node) {
  29. if (context.parserServices.getTemplateBodyTokenStore == null) {
  30. context.report({
  31. loc: { line: 1, column: 0 },
  32. message: 'Use the latest vue-eslint-parser. See also https://github.com/vuejs/eslint-plugin-vue#what-is-the-use-the-latest-vue-eslint-parser-error.'
  33. })
  34. return
  35. }
  36. if (!node.templateBody) {
  37. return
  38. }
  39. const sourceCode = context.getSourceCode()
  40. const tokenStore = context.parserServices.getTemplateBodyTokenStore()
  41. const tokens = tokenStore.getTokens(node.templateBody, { includeComments: true })
  42. let prevToken = tokens.shift()
  43. for (const token of tokens) {
  44. const spaces = token.range[0] - prevToken.range[1]
  45. if (spaces > 1 && token.loc.start.line === prevToken.loc.start.line) {
  46. context.report({
  47. node: token,
  48. loc: {
  49. start: prevToken.loc.end,
  50. end: token.loc.start
  51. },
  52. message: "Multiple spaces found before '{{displayValue}}'.",
  53. fix: (fixer) => fixer.replaceTextRange([prevToken.range[1], token.range[0]], ' '),
  54. data: {
  55. displayValue: sourceCode.getText(token)
  56. }
  57. })
  58. }
  59. prevToken = token
  60. }
  61. }
  62. }
  63. }
  64. }