8

What settings need to be configured to add a new line before and after method declaration in classes in typescript files using prettier plugin in vs code editor?

How can we achieve by writing any rule in .prettierrc or tslint.json file?

current behavior is

function one(){
// some code
}
function two(){
// some code
}

expected result

function one(){
// some code
}

function two(){
// some code
}

I have tried with below line in tslint.json

"lines-between-class-methods": "true"

but did not works

Gama11
  • 31,714
  • 9
  • 78
  • 100
xkeshav
  • 53,360
  • 44
  • 177
  • 245

3 Answers3

11

What @lakshan mentions is an ESLint rule. There is a TSLint rule that accomplishes what you are looking for but on in regards to class methods.

https://github.com/chinchiheather/tslint-lines-between-class-members

Run

npm install --save-dev tslint-lines-between-class-members

Add

tslint.json

{
  "rulesDirectory": [
    "node_modules/tslint-lines-between-class-members"
  ],
  "rules": {
    "lines-between-class-members": true,
  }
}
seangwright
  • 17,245
  • 6
  • 42
  • 54
1

lines-between-class-members is a built-in of ESLint, the replacement of TSLint which is now deprecated. This rule works for both TypeScript and JavaScript and --fix is supported. See https://eslint.org/docs/rules/lines-between-class-members for full details. You probably want to set exceptAfterSingleLine to true for TypeScript.

To make ESLint work for TypeScript you have to install npm packages @typescript-eslint/parser and @typescript-eslint/eslint-plugin and include both parser and plugin in your ESLint config. See typescript-eslint docs.

{
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }]
  }
}
Blaise
  • 13,139
  • 9
  • 69
  • 97
0

try this, inside your es-lint rules,

"lines-between-class-members" : ["error", "always"]

It will throw you an error if you violate the condition. & I think you must declare your functions inside a class in order that to work.

to add to that, you might not get auto-fix with prettier, because It turns out empty lines are very hard to automatically generate. The approach that Prettier takes is to preserve empty lines the way they were in the original source code.

Sankha Karunasekara
  • 1,636
  • 18
  • 19