附上demo地址gitlee
-
npx tyarn add typescript @vue/cli-plugin-typescript -D
-
npx tsc --init
-
修改 tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"allowJs": 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"
]
}
- 修改 main.js
将main.js 改为 main.ts
- 增加 src/vue-shim.d.ts src/shims-tsx.d.ts
// vue-shim.d.ts
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
// shims-tsx.d.ts
import Vue, { VNode } from 'vue'
declare global {
namespace JSX {
interface Element extends VNode {}
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any
}
}
}
- 修改 vue.config.js
module.exports = {
configureWebpack: (config) => {
config.resolve.extensions.push(...['.ts', '.tsx', '.js', '.json']);
},
};
- 修改组件: AboutView.vue 为例
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
data() {
return {
name: 'about'
}
}
})
</script>
- 修改组件: HomeView.vue 为例
<script lang="ts">
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
import Vue, { PropType } from "vue";
interface IObj {
name: string;
age: number;
}
export default Vue.extend({
name: "HomeView",
components: {
HelloWorld,
},
props: {
str: {
type: String,
},
obj: {
type: Object as PropType<IObj>,
},
fn: {
type: Function as PropType<() => void>,
},
},
data() {
return {
age: 13,
};
},
methods: {
getAge(age: string): number {
return parseInt(age);
},
},
});
</script>
- 安装eslint插件
npx tyarn add @typescript-eslint/eslint-plugin @typescript-eslint/parser vue-eslint-parser -D
- 修改配置文件.eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true
},
parser: "vue-eslint-parser",
extends: [
'plugin:vue/essential',
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
plugins: ['@typescript-eslint'],
parserOptions: {
parser: '@typescript-eslint/parser' // 解析 .ts 文件
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
- 重启
yarn serve
or
npm run serve