DEV Community

Cover image for Using ESLint and Prettier with VScode in an Angular Project πŸš€(outdated)
Andrei Voicu
Andrei Voicu

Posted on • Updated on

Using ESLint and Prettier with VScode in an Angular Project πŸš€(outdated)

In this setup guide you will learn how to use Prettier to take care of your code formatting and ESLint to take care of your code style in an Angular application.

Create an angular application using the angular-cli:

ng new ng-pretty
cd ng-pretty
Enter fullscreen mode Exit fullscreen mode

Install the required dependencies:

# Install ESLint
npm install --save-dev eslint

# Install additional plugins
npm install --save-dev @typescript-eslint/eslint-plugin eslint-plugin-prettier

# Install Prettier and Prettier-ESLint dependencies
npm install --save-dev prettier prettier-eslint eslint-config-prettier
Enter fullscreen mode Exit fullscreen mode

Add a configuration file for ESLint, named .eslintrc.json containing:

{
  "parser": "@typescript-eslint/parser", // Specifies the ESLint parser
  "extends": [
    "plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    "prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  "parserOptions": {
    "ecmaVersion": 2020, // Allows for the parsing of modern ECMAScript features
    "sourceType": "module" // Allows for the use of imports
  },
  "rules": {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
  }
}
Enter fullscreen mode Exit fullscreen mode
  • You can add your specific linting rules in the rules property.

It's a good idea not to format the dependencies folder, since every time you add a new dependency npm usually does that, for this you should add an .eslintignore file containing:

package.json
package-lock.json
dist
Enter fullscreen mode Exit fullscreen mode

Modify the lint script in your package.json:

"scripts": {
  "lint": "tsc --noEmit && eslint . --ext js,ts,json --quiet --fix",
}
Enter fullscreen mode Exit fullscreen mode

This will typecheck your app, and run the linter through all Javascript, JSON and Typescript files. Any ESLint errors that can be automatically fixed will be fixed with this command, but any other errors will be printed out in the command line.

At this point, ESLint will work correctly with TypeScript. You can lint your project’s JavaScript and TypeScript files by running npm run lint.

Add a configuration file for Prettier, named .prettierrc.json containing:

{
  "singleQuote": true,
  "trailingComma": "none",
  "endOfLine": "auto"
}
Enter fullscreen mode Exit fullscreen mode

you can configure prettier any way you like πŸ˜‰

Install the following Visual Studio Code extensions:

dbaeumer.vscode-eslint
esbenp.prettier-vscode
Enter fullscreen mode Exit fullscreen mode

Add the following to your .vscode/settings.json file:

{
  "[javascript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  },
  "[typescript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  },
  "[json]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  }
}
Enter fullscreen mode Exit fullscreen mode

And that’s it! You should now have complete Visual Studio Code integration. When you violate a linting rule, you’ll be visually alerted, and when you save a file, ESLint will attempt to fix any issues using Prettier. This should work for both JavaScript and TypeScript.

You can find the code for this tutorial here: ng-pretty

Top comments (15)

Collapse
 
snutij profile image
snutij • Edited

Hi dude, thanks you for pro tips !
But with ng new command it will create karma.conf.js and protractor.conf.js that are not compatible with somes eslint rules like no-empty-function or no-var-require. I must add them to eslintignore.

Except this, everything is fine. :)

Collapse
 
tstevanovich profile image
Tony Stevanovich

I've been looking for a guide like this. Thank you for putting this together.
Only things I changed from your article was
1: the addition of a .prettierignore file to format package.json, package-lock.json or the dist folder.
2: I added "trailingComma": "none" to the .prettierrc.json file.
3: I really don't like how prettier formats HTML files, so I changed up settings.json with this:
"[html]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "vscode.html-language-features"
},

Collapse
 
dreiv profile image
Andrei Voicu

I'm glad you found it useful :D

Collapse
 
cptdaydreamer profile image
CptDayDreamer • Edited

How to configure specific rules? If I add "no-empty-function": "off" to .eslintrc.json it won't be recognized. I still get the warning in my code. Where to set it then or why does it not work? Nice tutorial anyway but that's a problem for me. The warning in the code is: Unexpected empty method 'ngOnInit'.eslint@typescript-eslint/no-empty-function

Collapse
 
jpchip profile image
Jared Chapiewsky

I had the same problem! To resolve, I actually had to add "@typescript-eslint/no-empty-function": "off" to the .eslintrc.json file. The "@typescript-eslint/" was the important missing bit. You probably figured this out ages ago but wanted to add it here in case anyone else has this same problem.

Collapse
 
lahinouski profile image
Aliaksandr Lahinouski

Thank you Jared! Thank you so so much. Love you man.

Collapse
 
dacrypt profile image
David VelΓ‘squez • Edited

Hi, there seems to be a problem with your instructions.

npm run lint
> tsc --noEmit && eslint . --ext js,ts,json --quiet --fix

Version 4.0.2
Syntax:   tsc [options] [file...]

Examples: tsc hello.ts
          tsc --outFile file.js file.ts
          tsc @args.txt
          tsc --build tsconfig.json

Options:
 -h, --help                                         Print this message.
 -w, --watch                                        Watch input files.
 --pretty                                           Stylize errors and messages using color and context (experimental).
 --all                                              Show all compiler options.
 -v, --version                                      Print the compiler's version.
 --init                                             Initializes a TypeScript project and creates a tsconfig.json file.
 -p FILE OR DIRECTORY, --project FILE OR DIRECTORY  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
 -b, --build                                        Build one or more projects and their dependencies, if out of date
 -t VERSION, --target VERSION                       Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'.
 -m KIND, --module KIND                             Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'.
 --lib                                              Specify library files to be included in the compilation.
                                                      'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'es2019' 'es2020' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.asyncgenerator' 'es2018.asynciterable' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'es2019.array' 'es2019.object' 'es2019.string' 'es2019.symbol' 'es2020.bigint' 'es2020.promise' 'es2020.string' 'es2020.symbol.wellknown' 'es2020.intl' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint' 'esnext.string' 'esnext.promise' 
 --allowJs                                          Allow javascript files to be compiled.
 --jsx KIND                                         Specify JSX code generation: 'preserve', 'react-native', or 'react'.
 -d, --declaration                                  Generates corresponding '.d.ts' file.
 --declarationMap                                   Generates a sourcemap for each corresponding '.d.ts' file.
 --sourceMap                                        Generates corresponding '.map' file.
 --outFile FILE                                     Concatenate and emit output to single file.
 --outDir DIRECTORY                                 Redirect output structure to the directory.
 --removeComments                                   Do not emit comments to output.
 --noEmit                                           Do not emit outputs.
 --strict                                           Enable all strict type-checking options.
 --noImplicitAny                                    Raise error on expressions and declarations with an implied 'any' type.
 --strictNullChecks                                 Enable strict null checks.
 --strictFunctionTypes                              Enable strict checking of function types.
 --strictBindCallApply                              Enable strict 'bind', 'call', and 'apply' methods on functions.
 --strictPropertyInitialization                     Enable strict checking of property initialization in classes.
 --noImplicitThis                                   Raise error on 'this' expressions with an implied 'any' type.
 --alwaysStrict                                     Parse in strict mode and emit "use strict" for each source file.
 --noUnusedLocals                                   Report errors on unused locals.
 --noUnusedParameters                               Report errors on unused parameters.
 --noImplicitReturns                                Report error when not all code paths in function return a value.
 --noFallthroughCasesInSwitch                       Report errors for fallthrough cases in switch statement.
 --types                                            Type declaration files to be included in compilation.
 --esModuleInterop                                  Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
 @<file>                                            Insert command line options and files from a file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! newproject@0.93.0 lint: `tsc --noEmit && eslint . --ext js,ts,json --quiet --fix`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the newproject@0.93.0 lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/newprojectowner/.npm/_logs/2020-09-07T14_41_11_595Z-debug.log
Collapse
 
viltersten profile image
Viltersten

It would be nice to get links for all the features assignable in Prettier and in EsLint. Especially the former, as the latter can be googled easier.

Also, I'm not sure how they relate to each other. What if I set the first to allow quotation marks and the other to only accept apostrophes? Kind of confusing at the moment.

Collapse
 
guepardo190889 profile image
Seth Karim Luis Martinez • Edited

It does not work or I have not been able to make it work with the html files.

In my example I added a component called test and it made errors executing the lint.

As I read in the Prettier documentation, the --fix parameter should automatically correct html as well.

drive.google.com/file/d/1GHIMYOMu6...

Collapse
 
himanshugoel profile image
Himanshu Goel

When I setup these details and tried to run npm run lint, I receive below error -
No files matching the pattern "*/.{ts}" were found.

Collapse
 
dreiv profile image
Andrei Voicu • Edited

I will update the article, just to have time for it, things have changed, new version of eslint and prettier got out :D

Edit: Updated the article πŸ˜‰

Collapse
 
pedy711 profile image
pedy711

Hi Andrei, Thanks for your article. But I get the following error:
ESLint couldn't find the config "prettier/@typescript-eslint" to extend from. Please check that the name of the config is correct.

Collapse
 
vinodsantharam profile image
Vinod Santharam

Thanks man!

Collapse
 
dbrils profile image
dbrils

What is the prettier-eslint package used for? I see you added it to the dev dependencies, but I don't see it being used anywhere.