在vue新项目中用TypeScript---配置篇

1.npm下载依赖包

npm install typescript ts-loader tslint tslint-loader  tslint-config-standard  vue-property-decorator  vue-class-component

2.增加 tsconfig.json

可参考TypeScript-Vue-Start

{
  "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
App.vue
HelloWorld.vue
helloworld.vue

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值