Search code examples
reactjstypescriptprettier-eslint

Prettier, React Router 6, useParams hook, unexpected token


I've been smashing my face into this problem the entire morning.

I recently assembled a new project with React 18, React Router 6, TypeScript, Webpack 5, eslint, and prettier.

Things were going fine until I tried out the useParams hook, and now my linter keeps printing out the following error:

/.../index.tsx
  9:41  error  Parsing error: Unexpected token  prettier/prettier

✖ 1 problem (1 error, 0 warnings)

I have been searching around on Google, but I have not found anything talking about this issue directly. I'm not sure what to do at this point other than remove prettier from the project.

Here's my eslintrc:

{
    "root": true,
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "react",
        "@typescript-eslint",
        "prettier"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended"
    ],
    "settings": {
        "import/resolver": {
            "alias": [
                ["components", "./src/components"],
                ["routes", "./src/routes"],
                ["views", "./src/views"]
              ]
        },
        "react": {
            "version": "detect"
        }
    },
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    }
}

Prettier config:

{
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "bracketSameLine": false,
  "jsxSingleQuote": true,
  "parser": "babel",
  "printWidth": 80,
  "proseWrap": "preserve",
  "requirePragma": false,
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "endOfLine": "auto",
  "useTabs": false
}

and the offending page:

import React from 'react';
import { useParams } from 'react-router-dom';

type ParamTypes = {
  id: string
};

const Customer: React.FC = () => {
  const { id } = useParams<ParamTypes>();
  return <div>{id}</div>;
};

export default Customer;

According to Prettier, the offending character is the final parenthesis:

const { id } = useParams<ParamTypes>();
                                     ^

Solution

  • I figured it out.

    The issue was in my prettier config: "parser": "babel". According to the docs, this does not need to be set, since Prettier can infer which parser it needs to use based on the file.

    Removing this setting has briefly restored my sanity. Hooray.

    Mystery solved.