Svelte with prettier/eslint

Viewed 8364

I am trying to make an app using svelte to try it out.

I would like to setup prettier and eslint, I installed those dependencies and the extension for Svelte for VS Code.

  "dependencies": {
    "eslint": "^7.7.0",
    "eslint-plugin-svelte3": "^2.7.3",
    "prettier": "^2.0.5",
    "prettier-plugin-svelte": "^1.1.0",
    "save-dev": "0.0.1-security",
    "sirv-cli": "^1.0.0",
    "stylelint": "^13.6.1"
  }

Now, I am having trouble setting everything up.

I made

.eslintrc

{
  "plugins": ["eslint-plugin-svelte3"],
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "rules": {
    "semi": "error"
  }
}

.prettierrc

{
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true,
  "trailingComma": "es6"
}

and I would like autosave with settings.json under .vscode

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.prettier": true
  },
  "typescript.tsdk": "node_modules/typescript/lib",
  "eslint.validate": ["svelte"]
}

Now I tried to use this, but nothing happen when I save, neither when I execute

"fix": "npx eslint --fix \"src/**/*.svelte\"",
"format": "npx prettier --write \"src/**/*.svelte\""

Am I missing something ?

1 Answers

The formatting problems occur because in your settings you tell VSCode to format everything with the esbenp.prettier-vscode extension, which cannot handle Svelte files. Add this to your config and it should work.

  "[svelte]": {
    "editor.defaultFormatter": "svelte.svelte-vscode"
  },

As an alternative you can install prettier-plugin-svelte from npm. After a reload, Prettier will notice this plugin if it's in the same node_modules folder and defer formatting of Svelte file to it. This should also fix your "Svelte files do not get formatted when running npm run format" problem.

For reference: https://github.com/sveltejs/language-tools/tree/master/docs#my-code-does-not-get-formatted

The ESLint problem likely occurs because the plugin name is wrong and you are missing the overrides section which tells ESLint how to treat Svelte files:

module.exports = {
  plugins: [
    'svelte3'
  ],
  overrides: [
    {
      files: ['*.svelte'],
      processor: 'svelte3/svelte3'
    }
  ],
  ..
};

Reference for setup: https://github.com/sveltejs/eslint-plugin-svelte3#installation

Related