+ts
搭建vue2+ts项目
使用 vue-cli 创建
vue create 项目名称
- 1
-
Please pick a preset - 选择 Manually select features
-
Check the features needed for your project - 选择上 TypeScript ,软件开发定制特别注意点空格是选择,软件开发定制点回车是下一步
-
Choose a version of Vue.js that you want to start the project with - 选择 2.x
等到项目构建完成便可启动项目了,命令: yarn serve
或者npm run serve
>yarn serve
- 1
看到熟悉的页面,启动成功.
项目结构:
与之前的vue2项目比较 出现了几个比较特殊的文件之外,router.js变为router.ts,main.js 变为main.ts,其余的文件和vue2一样。
tsconfig.json
配置文件https://cn.vuejs.org/v2/guide/typescript.html#%E6%8E%A8%E8%8D%90%E9%85%8D%E7%BD%AE
shims-tsx.d.ts
允许.tsx 结尾的文件,在 Vue 项目中编写 jsx 代码
shims-vue.d.ts
主要用于 TypeScript 识别.vue 文件,Ts 默认并不支持导入 vue 文件
vue.config.js
进入项目目录发现没有 vue.config.js
,手动创建一个和package.json
同级
// const proxyConfig =// process.env.NODE_ENV === "production"// ? require("./proxy.pro.config")// : require("./proxy.dev.config");module.exports = { assetsDir: "static", runtimeCompiler: true, devServer: { host: "0.0.0.0", // 端口号 port: 8080, https: false, // https:{type:Boolean} //配置自动启动浏览器 open: true, //热更新 hot: true, //配置多个跨域 proxy: { } // proxy: proxyConfig.proxyList, },};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
如果遇到options.proxy should be {Object|Array}
错误,将
proxy:{}
- 1
改为
proxy:null
- 1
main.ts、router.ts和vue2内容一样没啥好说的
*.vue 文件
打开 views文件加下的 Home.vue
<template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" /> </div></template><script lang="ts">import { Component, Vue } from "vue-property-decorator";import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src@Component({ components: { HelloWorld, },})export default class Home extends Vue {}</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
<script>
标签上声明lang="ts"
,使用typescript语言- 引入 vue-property-decorator