Home

Awesome

build npm

eslint-plugin-sort-class-members

ESLint rule for enforcing consistent ES6 class member order.

Installation

Install ESLint and eslint-plugin-sort-class-members:

$ npm install eslint eslint-plugin-sort-class-members --save-dev

Note: If you installed ESLint globally (using the -g flag) then you must also install eslint-plugin-sort-class-members globally.

Usage

Add sort-class-members to the plugins section of your .eslintrc configuration file, and configure the rule under the rules section.

{
	"plugins": ["sort-class-members"],
	"rules": {
		"sort-class-members/sort-class-members": [
			2,
			{
				"order": [
					"[static-properties]",
					"[static-methods]",
					"[properties]",
					"[conventional-private-properties]",
					"constructor",
					"[methods]",
					"[conventional-private-methods]"
				],
				"accessorPairPositioning": "getThenSet"
			}
		]
	}
}

Or, using ESLint's Flat Config (eslint.config.js):

import sortClassMembers from "eslint-plugin-sort-class-members";

export default [
	// Use the default configuration shown above.
	sortClassMembers.configs["flat/recommended"],

	rules: {
		// Customize specific configuration properties
		"sort-class-members/sort-class-members": [
			2,
			{
				"accessorPairPositioning": "together",
				"stopAfterFirstProblem": true
			}
		]
  }
];

When using the default configuration (shown above), the following patterns are considered problems:

class Foo {
	b = 'bar';

	c() {}

	constructor() {} // error Expected constructor to come before method c

	static a() {} // error Expected static method a to come before property b
}

When using the default configuration (shown above), the following patterns are not considered problems:

class Foo {
	static a() {}

	b = 'bar';

	constructor() {}

	c() {}
}

Configuration

The rule accepts the following configuration properties:

{
  "order": [
    "constructor",
    "[event-handlers]", // reference the custom group defined in the "groups" property
    "[everything-else]" // a few groups are provided by default (see list below)
  ],
  "groups": {
    "event-handlers": [{ "name": "/on.+/", "type": "method" }]
  },
  "accessorPairPositioning": "getThenSet",
  "stopAfterFirstProblem": false
}

Members can be matched to positional slots using several criteria, including name (exact match or regexp), member type (method or property), and whether or not the member is static. Each match slot is described by an object with six properties, all of which are optional.

A few examples:

Note: You can simply use a string if you only want to match on the name.

The following groups are provided by default:

NOTE: Currently only class properties using the proposed syntax are matched by "type": "property". Properties added via assignment are not considered by this rule.

Acknowledgements

Inspired by the sort-comp rule from eslint-plugin-react.