前置要求
- 安装 Node.js (版本要求 >= 14, 高版本的 npm 安装依赖效率高,不容易出错)
需求
- 使用 typescript 开发 uni-app
- 基于 vscode & npm script 运行 uni-app,不依赖 HBuilderX
- 配置 eslint 进行代码约束
- 配置 husky 对代码的提交和推送进行约束: 提交前 eslint fix
步骤
使用 Vue Cli 创建项目
安装 vue-cli
1 | npm install -g @vue/cli |
创建 uni-app 项目1
2
3vue create -p dcloudio/uni-preset-vue my-project
# 选择 TypeScript 模板
运行项目1
npm run serve
配置支持 scss (node-sass & sass-loader)
uni-app 暂不支持高版本的 sass,使用以下版本组合
1 | npm i node-sass@4.14.1 sass-loader@7.3.1 -D |
配置支持 husky 提交约束
1 | npm i lint-staged@8.1.5 husky -D |
然后,添加 lint-staged 配置到 package.json中:1
2
3
4
5
6
7
8
9{
// ...
"lint-staged": {
"src/**/*.{js,ts,vue}": [
"eslint --fix",
"git add"
]
}
}
将以下脚本添加到 .husky/pre-commit 中:1
2
3
4
5
6
. "$(dirname "$0")/_/husky.sh"
echo 'pre-commit'
npx lint-staged
npm run fix
将以下脚本添加到 .husky/pre-push 中:1
2
3
4
. "$(dirname "$0")/_/husky.sh"
npm run lint
配置支持 eslint 约束
1 | npm i eslint@6.8.0 -D |
Next, create a .eslintrc.js config file in the root of your project, and populate it with the following:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44// eslint-disable-next-line no-undef
module.exports = {
root: true,
// parser: 'babel-eslint',
// parser: '@typescript-eslint/parser',
parserOptions: {
// parser: 'babel-eslint',
// sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
node: true,
es6: true
},
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:vue/recommended',
'@vue/typescript/recommended',
// 'plugin:vue/recommended'
],
rules: {
'vue/max-attributes-per-line': [1, {
'singleline': 10,
'multiline': {
'max': 1,
'allowFirstLine': false
}
}],
'vue/singleline-html-element-content-newline': 'off',
'vue/multiline-html-element-content-newline': 'off',
'vue/name-property-casing': ['error', 'PascalCase'],
'vue/no-v-html': 'off',
'vue/no-unused-components': [2, {
'ignoreWhenBindingPresent': true
}],
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
};
Next, create a .eslintignore file in the root of your project. This file will tell ESLint which files and folders it should never lint.
Add the following lines to the file:
1 | # don't ever lint node_modules |
最后,添加 npm 命令:1
2
3
4scripts: [
"lint": "npx eslint src --ext .js,.jsx,.ts,.tsx,.vue",
"fix": "npx eslint src --fix --ext .js,.jsx,.ts,.tsx,.vue"
]