Code formatting with prettier is not working in nest js

Viewed 106

I am using Visual Studio Code. In my Nest JS project, the code is not formatting according to prettier rules. I already set .prettierrc and .eslintrc. Also i have set formatOnSave: true from the settings.json file.

Portion of my settings.json file

  "editor.formatOnType": true,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },

My .eslintrc file -

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir: __dirname,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off'
  },
};

And finally my .prettierrc file -

{
  "useTabs": true,
  "tabWidth": 2,
  "semi": true,
  "singleQuote": false,
  "jsxSingleQuote": false,
  "trailingComma": "all",
  "bracketSpacing": true,
  "bracketSameLine": false,
  "arrowParens": "avoid",
  "importOrder": ["^[./]"],
  "importOrderSortSpecifiers": true,
  "importOrderSeparation": true
}

Can you please tell me what to do to format the code properly?

2 Answers
  1. Make sure prettier is enabled in VS Code
  2. Check the "prettier" logs (open a terminal, select the "output" tab. next you need to find Prettier in the list)

In my case the .prettierrc file was not in the root of the project and VS Code couldn't find it. (I just have to change the path to this file or move it to the root of the project)

One reason prettier will skip formatting a file is when the file has syntax error(s) in it. If prettier can't parse it, it errs on the side of caution and doesn't touch it.

Related