if you save a file in your project, the IDE should "autoformat" the file following a given ruleset (ESLint and Prettier configurations).
Example of adding semicolons on save:
-
Install eslint package to your project:
ng add @angular-eslint/schematics
-
Add the fix command to your project's package.json scripts area:
"scripts": { // ...other commands "lint:fix": "ng lint --fix" // ...other commands },
-
Install Prettier package to your project to get a source code formatter:
npm install prettier --save-dev
-
create .prettierrc.json file into your project's root folder with the following configuration:
{ "tabWidth": 2, "useTabs": false, "singleQuote": true, "semi": true, "bracketSpacing": true, "arrowParens": "avoid", "trailingComma": "es5", "bracketSameLine": true, "printWidth": 80, "endOfLine": "auto" }
-
create .prettierignore into your project's root folder:
# See http://help.github.com/ignore-files/ for more about ignoring files. # Compiled output /dist /tmp /out-tsc /bazel-out # Node /node_modules npm-debug.log yarn-error.log # IDEs and editors .idea/ .project .classpath .c9/ _.launch .settings/ _.sublime-workspace # Visual Studio Code .vscode/_ !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/_ # Miscellaneous /.angular/cache .sass-cache/ /connect.lock /coverage /libpeerconnection.log testem.log /typings # System files .DS_Store Thumbs.db
-
Install packages to connect ESLint and Prettier in your project:
npm install prettier-eslint eslint-config-prettier eslint-plugin-prettier --save-dev
-
Add the Prettier format command into your project's package.json file:
"scripts": { // ...other commands "prettier": "npx prettier --write ." // ...other commands },
-
Update .eslintrc.json file to use Prettier with ESLint:
... { "files": ["*.html"], "extends": [ "plugin:@angular-eslint/template/recommended", "plugin:@angular-eslint/template/accessibility", "plugin:prettier/recommended" ], "rules": {} } ...
and
"files": ["*.ts"], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@angular-eslint/recommended", "plugin:@angular-eslint/template/process-inline-templates", "plugin:prettier/recommended" ]
-
Activate formatting files on save feature in your IDE. All popular IDEs have the capability to run prettier if you save a file. Google "format on save" to your IDE to get the proper settings you need.
For IntelliJ IDE:
1. go to the Settings menu 2. search "Prettier" 3. select "Languages and frameworks" -> "Javascript" -> "Prettier" 4. choose "Automatic Prettier configuration" 5. check "Run on save" checkbox 6. click on Apply button 7. close settings, Prettier is ready