How to add new line after and before method declarations in classes using prettier?
Asked Answered
A

3

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

Aron answered 12/10, 2018 at 4:3 Comment(0)
F
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,
  }
}
Fireworks answered 21/1, 2019 at 15:27 Comment(0)
H
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 }]
  }
}
Hackneyed answered 11/5, 2021 at 10:16 Comment(0)
D
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.

Deforce answered 14/10, 2018 at 7:44 Comment(2)
does not help. I have added to my tslint.jsonAron
I think that is an es-lint rule...not sure if it works in tslint.json. I could be wrong.Keir

© 2022 - 2024 — McMap. All rights reserved.