说明
为什么要在vue项目中使用ts? 新公司给了一个关于vue项目的需求,又由于ts是JavaScript的超集,强类型数据,组件化友好。故我选择在vue项目中引入ts。
下载typescript和loader
npm install typescript ts-loader --save-dev
2.安装vue-property-decorator
npm install vue-property-decorator --save-dev
3. 配置vue.config.js添加下面的代码
configureWebpack: { resolve: { extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: {appendTsSuffixTo: [/\.vue$/], } } ] } }
4.新建tsconfig.json放在项目根目录
{"compilerOptions": {"target": "es5","module": "commonjs","strict": true,"strictNullChecks": true,"esModuleInterop": true,"experimentalDecorators": true}}
5. 在src根目录下新建vue-shim.d.ts 这个文件可以让vue识别ts文件(不加会报错)
declare module "*.vue" {import Vue from "vue";export default Vue;}
vue项目引入ts成功。喜欢的点个赞吧