vue-cli3引入ts
时间: 2023-06-29 12:03:00 浏览: 126
vue项目引入ts步骤(小结)
要在Vue-cli 3中使用TypeScript,需要先安装TypeScript和Vue的TypeScript声明文件。
1. 安装TypeScript和Vue TypeScript声明文件:
```
npm install typescript vue-class-component vue-property-decorator --save-dev
npm install @types/node @types/webpack @types/vue @types/vue-router @types/vuex --save-dev
```
2. 在项目根目录下创建一个`tsconfig.json`文件,用于配置TypeScript编译器的选项:
```
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
```
这里的配置项可以根据你的需求进行调整。
3. 修改项目的入口文件`main.js`,将其改为`main.ts`,并且使用`Vue.extend`来定义Vue组件:
```
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
```
4. 在`src`目录下创建一个`shims-tsx.d.ts`文件,用于声明Vue组件的类型:
```
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends Vue.VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any;
}
}
}
```
5. 在`src`目录下创建一个`shims-vue.d.ts`文件,用于声明Vue组件的类型:
```
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
```
6. 修改`package.json`文件,将`main.js`改为`main.ts`:
```
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"vue": "^2.6.10",
"vue-router": "^3.0.3",
"vuex": "^3.0.1"
},
"devDependencies": {
"@types/node": "^10.12.18",
"@types/vue": "^2.0.8",
"@types/vue-router": "^3.0.2",
"@types/vuex": "^3.0.0",
"typescript": "^3.3.3333",
"vue-class-component": "^6.0.0",
"vue-property-decorator": "^7.0.0",
"vue-template-compiler": "^2.6.10"
},
"main": "src/main.ts",
"browserslist": [
"> 1%",
"last 2 versions"
]
}
```
7. 运行`npm run serve`命令来启动开发服务器,开始使用TypeScript进行Vue开发。
阅读全文