本文主要介绍了vue与typescript集成配置最简教程(推荐),具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。
前言
vue的官方文档没有给出与typescript集成的具体步骤,网上其他的教程不是存在问题就是与vue-cli建立的项目存在差异,让人无从下手。
下面我就给出vue-cli建立的项目与typescript集成的最简配置。
初始化项目
首先用vue-cli建立webpack项目。这里为了演示方便,没有打开router和eslint等,可以根据自身情况打开。
# vue init webpack vue-typescript
? project name vue-typescript
? project description a vue.js project
? author
? vue build standalone
? install vue-router? no
? use eslint to lint your code? no
? setup unit tests with karma + mocha? no
? setup e2e tests with nightwatch? no
安装typescript相关依赖和项目其余依赖,用npm或cnpm
# cd /vue-typescript
# npm install typescript ts-loader --save-dev
# npm install
配置
修改目录下bulid/webpack.base.conf.js文件,在文件内module>rules添加以下规则
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendtssuffixto: [/\.vue$/],
}
},
在src目录下新建一个文件vue-shims.d.ts,用于识别单文件vue内的ts代码
declare module "*.vue" {
import vue from "vue";
export default vue;
}
在项目根目录下建立typescript配置文件tsconfig.json
{
"compileroptions": {
"strict": true,
"module": "es2015",
"moduleresolution": "node",
"target": "es5",
"allowsyntheticdefaultimports": true,
"lib": [
"es2017",
"dom"
]
}
}
重命名src下的main.js为main.ts
修改webpack.base.conf.js下的entry>app为'./src/main.ts'
修改src下的app.vue文件,在
<script lang="ts">
测试
下面可以测试是否集成成功,编辑src/components/hello.vue文件,修改
<script lang="ts">
import vue, {componentoptions} from 'vue'
export default {
name: 'hello',
data() {
return {
msg: 'this is a typescript project now'
}
}
} as componentoptions<vue>
</script>
运行项目
# npm run dev
测试成功,现在是一个typescipt项目了
进阶
配置官方推荐的vue-class-component,https://cn.vuejs.org/v2/guide/typescript.html
安装开发依赖
# npm install --save-dev vue-class-component
修改ts配置文件,增加以下两项配置
"allowsyntheticdefaultimports": true,
"experimentaldecorators": true,
改写我们的hello组件
<script lang="ts">
import vue from 'vue'
import component from 'vue-class-component'
@component
export default class hello extends vue {
msg: string = 'this is a typescript project now'
}
</script>
使用vue-class-component后,初始数据可以直接声明为实例的属性,而不需放入data() {return{}}中,组件方法也可以直接声明为实例的方法,如官方实例,更多使用方法可以参考其官方文档
https://github.com/vuejs/vue-class-component#vue-class-component
import vue from 'vue'
import component from 'vue-class-component'
// @component 修饰符注明了此类为一个 vue 组件
@component({
// 所有的组件选项都可以放在这里
template: '<button @click="onclick">click!</button>'
})
export default class mycomponent extends vue {
// 初始数据可以直接声明为实例的属性
message: string = 'hello!'
// 组件方法也可以直接声明为实例的方法
onclick (): void {
window.alert(this.message)
}
}
相关推荐:
vue 2.5中有关typescript的改进之处
介绍javascript和typescript的声明类型
分享typescript的一些小技巧
以上就是vue与typescript集成配置教程的详细内容。