- 安装ts-loader,typescript
yarn add ts-loader typescript - -d
- 新增tsconfig.json文件
{
"compilerOptions": {
// 与 Vue 的浏览器支持保持一致
"target": "es5",
// 这可以对 `this` 上的数据属性进行更严格的推断
"strict": true,
// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:
"module": "es2015",
"moduleResolution": "node",
"experimentalDecorators": true,
"sourceMap": true
},
"include": ["src"],
"exclude": [
"node_modules",
"dist"
]
}
- vue.config.js中配置loader
module.exports = {
chainWebpack: config=>{
c.module
.rule('ts-loader')
.test(/\.tsx?$/)
.exclude.add(fromSrc('node_modules'))
.end()
.use('ts-loader')
.loader('ts-loader')
.options({
appendTsSuffixTo: [/\.vue$/]
})
}
- 安装vue 针对typescript的支持的插件vue-class-component vue-property-decorator
yarn add vue-class-component,vue-property-decorator
- vue文件中script标签新增lang属性,值为ts,编写类型为typescript的Vue组件
<template>
<div>
<h1 @click="onClick">{{message}}</h1>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class MyComponent extends Vue {
message: string = 'Hello!'
onClick(): void {
window.alert(this.message)
}
}
</script>
<style scoped lang="scss">
</style>
- yarn serve运行项目,会发现报错:
ERROR TS18003: No inputs were found in config file 'tsconfig.json'. Specified 'include' paths were '["src"]' and 'exclude' paths were '["node_modules","dist"]'.
解觉方式是在src中随便新建一个ts文件即可。