【发布时间】:2020-08-27 02:31:42
【问题描述】:
我在 Visual Studio 代码编辑器中使用 Prettier 扩展已经很长时间了,但最近我正在用 Typescript 写 React。所以我需要配置 Prettier 来格式化 .tsx 文件。
【问题讨论】:
-
你有
prettier作为这个项目的依赖吗?
标签: reactjs typescript visual-studio-code prettier tsx
我在 Visual Studio 代码编辑器中使用 Prettier 扩展已经很长时间了,但最近我正在用 Typescript 写 React。所以我需要配置 Prettier 来格式化 .tsx 文件。
【问题讨论】:
prettier作为这个项目的依赖吗?
标签: reactjs typescript visual-studio-code prettier tsx
在 VScode 的 settings.json 中编辑设置
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
【讨论】:
扩展 iNeelPatel 的回答,我不得不在 VSCode JSON 设置中添加两行:
"[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }
【讨论】:
这将给出完美的解决方案
“我刚才也发生了同样的事情。我在设置中将 prettier 设置为默认格式化程序,它又开始工作了。我的默认格式化程序为空。”
https://github.com/microsoft/vscode/issues/108447#issuecomment-706642248
【讨论】:
我的使用情况
我设置的方式是使用 eslint 的 .eslintrc.json 文件。首先,在"extends"数组中,我添加了
"plugin:@typescript-eslint/recommended"
和
"prettier/@typescript-eslint"
然后,我将"parser" 设置为"prettier/@typescript-eslint"
最后,我在"plugins" 数组中添加了"@typescript-eslint"。
您需要获取几个 NPM 包(使用 -D 选项安装):
@typescript-eslint/eslint-plugin
@typescript-eslint/parser
作为参考,我的整个.eslintrc.json 文件:
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
"extends": [
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:prettier/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"project": "./src/tsconfig.json",
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": ["react", "@typescript-eslint", "jest"],
"rules": {
"react/react-in-jsx-scope": "off"
}
}
希望这会有所帮助。
【讨论】:
一个简单的 UI 替代方案:
【讨论】: