在vue新项目中用TypeScript---配置篇
1.npm下载依赖包npm install typescript ts-loader tslint tslint-loadertslint-config-standardvue-property-decorator2.增加 tsconfig.json可参考TypeScript-Vue-Start{"exclude": ["node_modules"],"compilerOptions": {"al
·
1.npm下载依赖包
npm install typescript ts-loader tslint tslint-loader tslint-config-standard vue-property-decorator vue-class-component
2.增加 tsconfig.json
{
"exclude": [
"node_modules"
],
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowJs": true,
"module": "esnext",
"target": "esnext",
"moduleResolution": "node",
"experimentalDecorators": true,
"isolatedModules": true,
"typeRoots": [
"./types",
"./node_modules/vue/types"
],
"lib": [
"esnext",
"dom"
],
"sourceMap": true,
"pretty": true
},
"include": [
"./src/**/*"
]
}
3.webpack.base.conf.js 中的配置
resolve: {
extensions: ['.js', '.vue', '.json', 'ts', 'tsx'], // 新增了'ts', 'tsx'
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
{
test: /\.ts$/, // 用于加载项目中的ts文件
exclude: /node_modules/,
enforce: 'pre',
loader: 'tslint-loader'
},
{
test: /\.tsx?$/, // 用于加载项目中的tsx文件
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
}]
4.重命名main.js
- 将main.js重命名为main.ts
- 在webpack.base.conf.js中修改入口的文件名 entry: {app: ‘./src/main.ts’}
5.在main.ts同级目录下添加shims-tsx.d.ts(如果没有用tsx 语法就不用) 和 shims-vue.d.ts
// vue/cli中的shims-tsx.d.ts
// 作用: 为 JSX 语法的全局命名空间
// 这是因为基于值的元素会简单的在它所在的作用域里按标识符查找
// 此处使用的是无状态函数组件的方法来定义, 当在tsconfig内开启了jsx语法支持后, 其会自动识别对应的.tsx结尾的文件
import Vue, { VNode } from 'vue'
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any
}
}
}
// vue/cli中的shims-vue.d.ts
// 作用:为项目内所有的 vue 文件做模块声明, 毕竟 ts 默认只识别 .d.ts、.ts、.tsx 后缀的文件
import Vue from "vue";
import VueRouter, { Route } from "vue-router";
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
declare module "vue/types/vue" {
interface Vue {
$router: VueRouter; // 这表示this下有这个东西
$route: Route;
$https: any;
$urls: any;
$Message: any;
$Modal: any;
}
}
6.实例参考
在启动项目过程中会报一些错,可参考以下链接
typescript简单使用
typescript+vue踩过的坑-常见报错
webpack安装ts-loader后解析typescript运行报错webpack和ts-loader的版本不匹配。
App.vue
HelloWorld.vue
更多推荐
已为社区贡献1条内容
所有评论(0)