Mastodon hachyterm.io

In this article I will show you how to setup ESLint and Prettier for a Svelte.js project.

1. Installation

You need to install the following packages as dev dependencies:

npm install --save-dev prettier eslint prettier-plugin-svelte eslint-plugin-svelte3

2. Configuration

2.1. ESLint

Create an .eslintrc.json file in your project root directory:

{
  "env": {
    "browser": true,
    "es6": true
  },
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 2019,
    "sourceType": "module"
  },
  "plugins": ["svelte3"],
  "extends": ["eslint:recommended"],
  "overrides": [
    {
      "files": ["**/*.svelte"],
      "processor": "svelte3/svelte3"
    }
  ],
  "rules": {
    // ...
  }
}

You can see a list of available ESLint rules on the official website. (Or you can use the default settings and remove the "rules" part of the configuration.)

It also makes sense to ignore the default rollup.config.js file. Create a new file .eslintignore with the following content:

rollup.config.js

2.2. Prettier

You also need a configuration file for prettier. Create a file called .prettierrc.json in your project directory. These are my preferred settings:

{
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true,
  "trailingComma": "es5",
  "plugins": ["prettier-plugin-svelte"]
}

The important entry is the plugins entry, the rest are options that I like. You can adjust the configuration to your liking.

You can see all options at the official prettier homepage.

If you want to know more about how to run prettier and eslint together, you can read the prettier documentation.

3. How to Use

You can format the code with the prettier CLI. Assuming you want to format your main app file in src/App.svelte:

prettier --write --plugin-search-dir=. src/App.svelte

You can also run the ESlint CLI:

eslint --fix src/App.svelte

Or you can use package.json to create a script to format all files with a .svelte and a .js extension. Add this script to package.json:

{
  "scripts": {
    "fix": "npx eslint --fix \"{,!(node_modules|public)/**/}*.{js,svelte}\"",
    "format": "npx prettier --write \"{,!(node_modules|public)/**/}*.{js,svelte}\""
  }
}

The script makes use of a glob to format files recursively.
It ignores the node_modules and the public folder, then formats all files with .js or .svelte extension.

Further Reading