Eslint custom rule without plugin(Without publishing to npm)

In this post, I will show you how to create a custom rule using the ESLint plugin.

What are ESLint Plugins

It’s an extension for ESLint that will enforce rules that are not implemented into the ESLint core. For example, if you want to force that nobody should use alert in their code, you can write your own plugin to force this rule.

Writing custom rules requires basic knowledge of javascript and node.js. You can install the plugin from the npm store, but you can also write custom rules without the plugin according to project needs. The problem with developing the custom eslint rule is to publish to npm and then test, but here I will show you how to test the custom eslint without publishing to npm store.

A simple rule

Let’s suppose you want to restrict the use of template literal in your code (Not very useful maybe, but for demonstration purposes of this guide, it will suffice.)

const a=`Hello world` //invalid
const a='Hello world'//valid

Structure of eslint plugin

The structure of the eslint plugin is as below

module.exports = {
    rules: {
        "rule-name": {
            create: function (context) {
                // rule implementation ...

Setting up our ESLint plugin

mkdir eslint-plugin-no-template-literals
cd eslint-plugin-no-template-literals
npm init -y
npm install -D eslint

How to implement our rule


An ESLint rule contains 2 main parts:

  • meta: an object where we will specify the usage of our rule.
  • createA function will return an object with all the methods that ESLint will use to parse our statement. Each method returned is an AST node.

You can visit AST Explorer for more information

create index.js file in your newly created folder and paste the following code

module.exports = {
    rules: {
        "no-template-literals": {
            create: function (context) {
                return {
                    TemplateLiteral(node) {
              , 'Do not use template literals');

The above code is self-explanatory. In AST template literal node is represented by TemplateLiteral eslint scan the source code of javascript, and when it found the template literal, it shows the error

How to use

Once you’re done, in your project root, add the plugin as a dependency using npm

npm add --dev file:./eslint-plugin-no-template-literals

Notice the file:./eslint-plugin-no-template-literals part. This syntax will allow us to install a package that is on our local file system.

Configure the newly created rule

Finally, add the plugin and rule to your eslintrc file. You can do that like so:

// eslintrc.js  
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module"
    "plugins": [ "no-template-literals" ],
    "rules": {
        "semi": "error",
        "no-template-literals/no-template-literals": 1

remove eslint-plugin prefix

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post