[纯干货]三步Vue2改造Typescript+CompositionApi

992 阅读1分钟

请确保你有 Vue composition apitypescript 的开发经验, 以免改造过后你反而不会用.

如果你本来是用Class的Vue2.x+Typesciprt项目

npm 还是 yarn 或者 pnpm 都一样, 无所谓, 注意依赖版本.

0 准备一个Vue2.x项目

1 添加项目依赖

三选一

npm install @vue/cli-plugin-typescript@~4.5.0 typescript @vue/composition-api
yarn add @vue/cli-plugin-typescript@~4.5.0 typescript @vue/composition-api
pnpm add @vue/cli-plugin-typescript@~4.5.0 typescript @vue/composition-api

2 添加声明文件和ts配置

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

src/shims-tsx.d.ts

import Vue, { VNode } from 'vue'

declare global {
  namespace JSX {
    // tslint:disable no-empty-interface
    interface Element extends VNode {}
    // tslint:disable no-empty-interface
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [elem: string]: any
    }
  }
}

src/shims-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

3 注册 Composition Api

main.js 改成 main.ts

src/main.ts

import CompositionApi from '@vue/composition-api';
Vue.use(CompositionApi);

结语

记得把 <script> 修改成 <script lang="ts"> .

怎么用 compostion Api

Help

如果有 eslint

安装 eslint 依赖, 三选一.

npm install @typescript-eslint/eslint-plugin@^4.18.0 @typescript-eslint/parser@^4.18.0 @vue/eslint-config-typescript@^7.0.0
yarn add @typescript-eslint/eslint-plugin@^4.18.0 @typescript-eslint/parser@^4.18.0 @vue/eslint-config-typescript@^7.0.0
pnpm add @typescript-eslint/eslint-plugin@^4.18.0 @typescript-eslint/parser@^4.18.0 @vue/eslint-config-typescript@^7.0.0

修改 .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
  },
};

如果本来是 vue-class-component 类TS的Vue2.x项目

只需要

npm install @vue/composition-api typescript@^4

然后注册 composition api 即可, 注意 typescript 的版本要大于 4 .