Search code examples
javascriptvisual-studio-codeformattingformatter

Formatter for VSCode which puts a space before a colon


At my new job the convention is to put a space before the colon like so:

{
    "a" : "1"
}

Is there any formatter, a setting, or similar which does this for VSCode? I tried prettier, but that just removed all the spaces. Language is javascript, if that matters

Edit: I know how to use a formatter, I just don't find one that will put a space before a colon. Maybe there's one that allows me to use regex for formatting?


Solution

  • It is possible using ESLint https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint + it's option key-spacing https://eslint.org/docs/latest/rules/key-spacing ...

    .eslintrc.json

    {
        ...,
        "rules": {
            ...,
            "key-spacing": [
                "error",
                {
                    "afterColon" : true,
                    "beforeColon" : true,
                    "mode": "strict"
                }
            ]
        }
    }
    

    Longer answer if you are not familiar with ESLint:

    • in project root run npm install eslint (or probably could be installed globally)
    • in project root run ./node_modules/.bin/eslint --init or npm init @eslint/config to configure .eslintrc.json
    • maybe restart of VSCode is needed

    Note: .eslintrc.json can be used in root and also in subfolders to maintain different ESLint options (for e.g. resources-frontend-browser files and resources-backend-nodejs files)