更漂亮地报告 JSX 中的语法错误

问题描述 投票:0回答:1

刚刚启动了一个新的 React 项目并决定在其中使用 Prettier。然而,在我的所有

.tsx
文件中,Prettier 报告了 JSX 第一行的语法错误。例如:

src/components/layout/Layout.tsx

function Layout(): React.ReactElement {
  return (
    <div className="layout-component">
      <header>
        <span>Installations</span>
        <span>Projects</span>
      </header>
    </div>
  );
}

export default Layout;

结果:

$ npx prettier src/components/layout/Layout.tsx 
src/components/layout/Layout.tsx
[error] src/components/layout/Layout.tsx: SyntaxError: Unexpected token, expected "," (3:9)

package.json
中的相关版本:

    "react": "^18.2.0",
    "react-dom": "^18.2.0"

    "@trivago/prettier-plugin-sort-imports": "^4.3.0",
    "prettier": "^3.2.5",
    "typescript": "^5.0.2",

.prettierrc

{
  "tabWidth": 2,
  "printWidth": 100,

  "plugins": ["@trivago/prettier-plugin-sort-imports"],
  "importOrder": ["^[./]"],
  "importOrderParserPlugins": ["typescript"],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "allowUmdGlobalAccess": false,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "forceConsistentCasingInFileNames": true,
    "noImplicitOverride": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noPropertyAccessFromIndexSignature": true,
    "noUncheckedIndexedAccess": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "strict": true,
    "verbatimModuleSyntax": true
  },
  "include": ["src"]
}
reactjs typescript prettier
1个回答
0
投票

经过几天的摆弄,我发现有问题的部分位于 Prettier 配置中:

  "importOrderParserPlugins": ["typescript"],

删除它可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.