Enable code formatting for apex in vs code

Telegram logo Join our Telegram Channel

Salesforce blog has recently published an article about how to enable code formatting for Apex Code in Visual Studio Code. Today I am going to share the detailed steps about how to enable code formatting. 

Before we start you need to have these things on your computer, please ignore if you already have it and skip to the next section.

I hope you are ready with all the setup. Let me know if you face any problems while setup. Ok so let's move on!


Steps to Enable Apex code formatting in Visual Studio Code

1. First, install the Prettier - code formatter.

2.  Now, check if you have package.json if you don't have then run the command npm init and keep the default settings.

3. Run the command npm install --save-dev --save-exact prettier prettier-plugin-apex
Note: You will need to run the above command for all of your workspaces at once.
4. Restart Visual Studio Code.

5. Once the installation is complete, we will do a few more steps. By default prettier uses spaces to format the code. Also, you can choose the length of the tab, by default it is 2, personally, I like tab-width of 4.

6. Now click Ctrl/Command + p to open the file search .prettierrc in files, if it does not exist in your workspace, please create.
{
    "trailingComma": "none",
    "plugins": ["prettier-plugin-apex", "@prettier/plugin-xml"],
    "overrides": [
        {
            "files": "**/lwc/**/*.html",
            "options": {
                "parser": "lwc"
            }
        },
        {
            "files": "*.{cmp,page,component}",
            "options": {
                "parser": "html"
            }
        },
        {
            "files": "*.{trigger,cls}",
            "options": {
                "parser": "apex"
            }
        },
        {
            "files": "*.{apex}",
            "options": {
                "parser": "apex-anonymous"
            }
        }
    ]
}

Now we will set the tabWidth and useTabs in the config, for that, you need to add just add below code inside the above config file.
"useTabs": true,
"tabWidth": 4,
"printWidth": 120
Ok, that's it you are all set!


Bonus Tip

You can also enable format on save so that the code is auto formatted whenever you save the file.
1. Goto File -> Preferences -> Settings 
2. Search format on save, then check the checkbox in from of "Format On Save".
apex-code-format-on-save


You will also like



Resources

No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com