【问题标题】:How to use TypeScript with vue and no modules如何在没有模块的情况下使用带有 vue 的 TypeScript
【发布时间】:2018-10-14 05:43:15
【问题描述】:

package.json我有

"devDependencies": {    
   "vue": "2.5.16"
}

这给了我index.d.ts, vue.d.tsso on 中的node_modules\vue\types。起初我在做new Vue({...});之类的事情时遇到了找不到vue((TS) Cannot find name 'Vue')的问题。阅读this 线程后,我通过添加custom.d.ts 文件来修复它:

import _vue = require('vue');

declare global {
    const Vue: typeof _vue;
}

并使用/// <reference path="../Declarations/custom.d.ts" /> 引用它

显然原因是vue的声明是外部模块格式(使用export),如果没有使用模块系统,则需要全局模块。

但现在 IntelliSense 给了我:"(TS) Cannot use 'new' with an expression whose type lacks a call or construct signature." 并且构建失败。

我正在使用带有 outFile 且没有模块的 TypeScript 2.8(只有 reference xml cmets)。

编辑:我以为我通过使用找到了答案

const Vue: typeof _vue.default;

这使得new Vue() 语句的错误消失。但是当我尝试声明Vue 类型的变量时,我再次收到Cannot find name 'Vue' 错误:

var app = new Vue({}); // Works
var app2:Vue = new Vue({}); // Doesn't work

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    我在custom.d.ts 中运行了以下基础知识:

    import * as _vueIndex from "vue";
    import * as _vue from "vue/types/vue";
    
    declare global {
        const Vue: _vueIndex.VueConstructor; // related to vue.d.ts "export const Vue: VueConstructor;"
    
        namespace Vue {
            //type Vue = typeof _vueIndex.default; // For some reason this becomes VueConstructor interface instead of Vue interface
            type Vue = _vue.Vue;
            type CreateElement = _vueIndex.CreateElement;
            type CombinedVueInstance<Instance extends Vue, Data, Methods, Computed, Props> = _vue.CombinedVueInstance<Instance, Data, Methods, Computed, Props>;
            /*Other interfaces*/
        }
    }
    

    现在可以执行以下操作:

    var app: Vue.CombinedVueInstance<Vue.Vue, any, VmMethods, any, any> = new Vue({
        el: '#app',
        methods: new VmMethods()
    });
    
    console.log(app.toggleSidebar()); // toggleSidebar is a public function in VmMethods
    console.log(app.nonExisting()); // ReSharper gives correct cannot resolve error but TypeScript still transpiles for some reason, which gives a run time error
    

    ReSharper 仍然提供 Symbol Vue cannot be properly resolved, probably it is located in inaccessible module,但 TypeScript 可以转译并运行良好。

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 2017-03-13
      • 2019-03-21
      • 2019-11-06
      • 2018-03-11
      • 1970-01-01
      • 2018-09-26
      • 2015-12-17
      • 2023-03-03
      相关资源
      最近更新 更多