Skip to content

moo-w/eslint-plugin-snippet

Repository files navigation

eslint-plugin-snippet

npm version npm downloads

Comment-as-snippet for one-off codemod with ESLint.

eslint-plugin-snippet.example.mov

Introduction

This plugin is very much inspired by eslint-plugin-command by Anthony Fu. This plugin also serves as a micro-codemod tool triggers by special comments on-demand, reuse the infrastructure of ESLint.

Installation

Install the eslint-plugin-snippet package:

npm i eslint-plugin-snippet -D

In your flat config eslint.config.mjs:

// eslint.config.mjs
import snippet from 'eslint-plugin-snippet/config'

export default [
  // ... your other flat config
  snippet(),
]
Legacy Config

While no longer supported, you may still use the legacy .eslintrc.js file:

// .eslintrc.js
module.exports = {
  plugins: [
    'snippet'
  ],
  rules: {
    'snippet/snippet': 'error',
  },
}

Plugin Configuration

You can configure the plugin by passing an object to the snippet function.

// eslint.config.mjs
import snippet from 'eslint-plugin-snippet/config'
import { builtInSnippets } from 'eslint-plugin-snippet/snippets'

export default [
  // ... your other flat config
  snippet({
    commandPrefix: ';',
    separator: '>',
    ignoreIndicator: '_',
    snippets: builtInSnippets,
  }),
]

One of the built-in snippets is function:

export default {
  name: 'function',
  command: 'f',
  template: `function fn($1) {
  $0
}`,
}

For examle, with the above configuration, you can trigger the snippet by //;f>body>param1, param2, which will be expanded to:

function fn(param1, param2) {
  body
}

//;f>_>param will be expanded to:

function fn(param) {

}

Custom Snippets

It's also possible to define your custom snippets.

// eslint.config.mjs
import { builtInSnippets, defineSnippets } from 'eslint-plugin-snippet/snippets'

const snippets = defineSnippets([
  ...builtInSnippets,
  {
    name: 'console.log',
    command: 'c',
    template: 'console.log($0)',
  },
  {
    name: 'function',
    command: 'f',
    template: `function fn($1) {
  $0
}`,
  },
])

As you can see, the index of the snippet-slots starts from 0: $0

Usage

  • Command Only: //;f
    function fn() {
    
    }
  • Command with slots: //;f>body>param
    function fn(param) {
      body
    }
  • Ignore: //;f>_>param
    function fn(param) {
    
    }
  • Escape character: //;c>'<test\>\;'
    console.log('<test>;')
  • Commnd nesting: //;f>;f>>;c>>>test>>test
    function fn() {
      function fn(test) {
        console.log(test)
      }
    }

Built-in Snippets

TODOs

  • support something like ;>;b>>testb1>>testb2>testa1>;c>>;d>>>testd1
  • support escape character

About

Comment-as-snippet for one-off codemod with ESLint

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published