typescriptvisual-studio-codenestjseslintprettier

Code formatting with prettier is not working in nest js


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?


Solution

  • I have solved this issue by fixing my setting.json file.

    I just make editor.formateOnSave: true for individual language. Like this way

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

    This works for me.

    Another solution was running prettier command. prettier --write \"src/**/*.ts\" \"test/**/*.ts\"

    But for using this command according to my .prettierrc and .eslintrc file you have to ensure some packages as the dev dependency.

    Most of the packages come from the nest js boilerplate. If you have not found any package from the boilerplate then install by yourself.

    Hopefully, this will be a great solution for those, who are facing this kind of problem like me. Have a good day!