@jay-es/eslint-plugin-vue-sort-components
Version:
A plugin for ESLint to keep order of component names
64 lines (63 loc) • 2.34 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortComponentsRule = void 0;
const natural_compare_1 = __importDefault(require("natural-compare"));
const getKeyName = (node) => node.key.type === "Identifier" ? node.key.name : "";
const getArgName = (arg) => arg.type === "Identifier" ? arg.name : "";
const compareNodes = (a, b, sortSpreads) => {
if (a.type === "Property" && b.type === "Property") {
return (0, natural_compare_1.default)(getKeyName(a), getKeyName(b));
}
if (a.type === "SpreadElement" && b.type === "SpreadElement") {
return sortSpreads
? (0, natural_compare_1.default)(getArgName(a.argument), getArgName(b.argument))
: 0;
}
return a.type === "SpreadElement" ? -1 : 1;
};
exports.sortComponentsRule = {
meta: {
type: "layout",
fixable: "code",
schema: [
{
type: "object",
properties: {
sortSpreads: { type: "boolean" },
},
additionalProperties: false,
},
],
messages: {
sortComponents: "Component names must be sorted.",
},
},
create(context) {
const sortSpreads = context.options[0]?.sortSpreads ?? false;
return {
Property(node) {
const { value } = node;
if (getKeyName(node) !== "components" ||
value.type !== "ObjectExpression") {
return;
}
const { properties } = value;
const sorted = [...properties].sort((a, b) => compareNodes(a, b, sortSpreads));
const sameOrder = properties.every((v, i) => v === sorted[i]);
if (sameOrder) {
return;
}
context.report({
node,
messageId: "sortComponents",
fix(fixer) {
return properties.map((prop, i) => fixer.replaceText(prop, context.sourceCode.getText(sorted[i])));
},
});
},
};
},
};