vue2 升级 vue3 小tips

1,416 阅读1分钟

vue3 对应的部分生态库升级

"vue": "3.0.11",
"@fortawesome/vue-fontawesome": "3.0.0-3",
"vue-i18n": "^9.1.4",
"vue-router": "4.0.6",
"vuex": "4.0.0",

vue3 对应的 devDependencies 工具库升级

"@vue/cli": "4.5.12",
"@vue/cli-plugin-babel": "4.5.12",
"@vue/cli-plugin-eslint": "4.5.12",
"@vue/cli-plugin-router": "4.5.12",
"@vue/cli-plugin-vuex": "4.5.12",
"@vue/cli-service": "4.5.12",
"@vue/compiler-sfc": "3.0.11",

注意:要跟随全局的 vue-cli 升级至最新版本

vue3 对应的 typescript、eslint 支持

// devDependencies
"typescript": "^4.2.4",
"@types/node": "^14.14.37",
"@typescript-eslint/eslint-plugin": "^4.22.0",
"@typescript-eslint/parser": "^4.22.0",
"@vue/cli-plugin-typescript": "4.5.12",
"@vue/eslint-config-standard": "^5.1.2",
"@vue/eslint-config-typescript": "^7.0.0",
"eslint": "^7.24.0",
"eslint-plugin-vue": "^7.9.0",

// 注意这个,因为 eslint-config-standard 已经不需要安装这个插件了
// 而 @vue/eslint-config-standard 需要,所以还是需要安装
"eslint-plugin-standard": "^5.0.0", 

更标准的 JS eslint

// devDependencies
"eslint-config-standard": "^16.0.2",
"eslint-config-standard-with-typescript": "^20.0.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",

这个 standard 真的是神器,特别是配合 vscode 对应的自动格式化,详见这篇文章 《vscode 配置实现 针对 eslint 自动格式化

tsconfig.json 配置项

{
  "compilerOptions": {
    "target": "es2019",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "src",
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

eslint 配置项

extends: [
    'plugin:vue/vue3-recommended',
    '@vue/standard',
    '@vue/typescript',
    'standard',
    'standard-with-typescript'
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    // https://stackoverflow.com/questions/58510287/parseroptions-project-has-been-set-for-typescript-eslint-parser
    project: './tsconfig.eslint.json'
  },

tsconfig.eslint.json 配置

// https://stackoverflow.com/questions/58510287/parseroptions-project-has-been-set-for-typescript-eslint-parser
{
  "extends": "./tsconfig.json",
  "include": [
    "./src/**/*",
    ".eslintrc.js",
    "**/*.config.js",
    "babel.config.js",
    "./scripts/"
  ]
}

添加 git hook 做 eslint 检查

"devDependencies": {
  "lint-staged": "10.5.4",
},
"gitHooks": {
  "pre-commit": "lint-staged"
},
"lint-staged": {
  "*.{js,jsx,vue,ts}": [
    "vue-cli-service lint",
    "git add"
  ]
}