利用editorconfig, prettier, eslint
背景
马上就要大学毕业工作了,实习过程中意识到自己以前一直不在意的团队协作中的代码规范重要性。现在整理一下供以后温习,写的很随意,仅供参考。
vscode 中的 editorconfig, prettier, eslint
三者是渐进的过程。
editorconfig 配置编码时的代码风格,prettier 配置编码后的保存时的规范,eslint 和 prettier 类似,但 prettier 不会仅仅是定义规范,不会对不符合规范的代码抛出错误或警告,eslint 则会检查语法,在例如变量未定义时抛出错误。
editorconfig 配置
- 安装 editorconfig 包
npm install -g editorconfig - 安装 vscode 扩展
ext install EditorConfig - 在项目根目录新建.editorconfig 文件
配置参考:
1 | |
prettier 配置
- 安装 prettier 包
npm install -g prettier - 安装 prettier for vscode 插件
- 新建.prettierrc.js 文件
配置参考:全部参数here
1 | |
vscode 中集成 prettier
1 | |
update
- 2020-03-28 使用配置文件的场合将vscode的默认选项屏蔽一下,否则可能有冲突, 具体: 在
setting.json末尾加上"prettier.requireConfig": true(使用配置文件格式化)
js 中 eslint 配置
- 安装 eslint 包
npm install -g eslint或npm install --save-dev prettier - 初始化 eslint 文件
eslint --init, 这里我选择 json 文件 eslint 不生效不知道为什么,换成 js 文件就好了。 - 配置 .eslintrc.js 文件
配置参考:
1 | |
Typescript 中 eslint 配置
2019.1 开始 TS 官方不再使用 tslint,建议使用 eslint 进行代码规范
- 在项目中安装 eslint
npm install --save-dev eslint - eslint 无法识别 ts 的部分语法,安装 ts 的解析器替换默认解析器
npm install --save-dev typescript @typescript-eslint/parser - 安装对 eslint 默认规则补充的包
npm install --save-dev @typescript-eslint/eslint-plugin - 新建.eslintrc.js 文件(不知道为啥 json 文件没效果)
配置如下:
1 | |
遇到ImportDeclaration should appear when the mode is ES6 and in the module context报错,在.eslintrc.js 中加入以下配置:
1 | |
vscode 中集成 eslint 检查并在保存时自动修复
在setting.json文件中加入对 ts 的检查
1 | |
(精)使用 AlloyTeam 的 ESLint 配置
alloy 团队的 eslint 配置去掉了糟粕,并且不再包含代码格式的规则,把其交给更专业的 prettier
- 安装
npm install --save-dev eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-alloy - 添加配置如下:(可以将 parser 和 plugin 去掉了)
1 | |
Vue with Typescript
建议直接使用官方提供的脚手架, 引用官网的一句话:
The most rules of eslint-plugin-vue require vue-eslint-parser to check
<template>ASTs.
由于vue是html+ts的特殊模板文件性质,使上述的ts扩展无法对.vue进行解析, 我尝试配置发现各种各样的问题,还是官方脚手架一键操作简单,只能说…真香
- 安装脚手架
vue-cli
1 | |
- 新建项目
vue create your-project-name, 放个配置例子


- 加入上述的
.editorconfig和.prettierrc.js文件, 就可以愉快地用ts开发vue了.
node-sass ?? dart-sass ??
由于node-sass使用C++开发, 安装node-sass可能会遇到卡死/下载失败等问题(博主也遇到了), 官方现在也推荐使用dart-sass
参考资料:
editorconfig vs prettier vs eslint
editorconfig 配置
prettier 配置
eslint 配置
eslint 中 js 规范配置参考
ImportDeclaration should appear when the mode is ES6 and in the module context 报错解决
typescript 配置代码规范