Augmenting vue.js in typescript

Arc*_*heg 3 typescript vue.js

I'm trying to augment vue js with additional mapping. I'm following this: https://v2.vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins

I have created a file vue.d.ts under ./Definitions (relative to my main.ts) I have referenced it in my main.ts:

require("./Definitions/vue.d.ts");
Run Code Online (Sandbox Code Playgroud)

In vue.d.ts I've put:

 // 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
    // 3. Declare augmentation for Vue
    interface Vue {
        $myProperty: string
    }
}
Run Code Online (Sandbox Code Playgroud)

But this:

var vm = new Vue()
console.log(vm.$myProperty);
Run Code Online (Sandbox Code Playgroud)

Doesn't resolve.

I've tried changing declare module 'vue/types/vue' to just declare module 'vue'. This gives me an error: "Cannot augument module 'vue' because it resolves to a non-module entity"

The original vue typings are located under {projectDir}\node_modules\@types\vue\index.d.ts. I'm using webpack.

How do I do it properly?

Har*_*til 5

假设您的项目有tsconfig.json,您应该设置以下内容compilerOptions

{
    "compilerOptions": {

        "baseUrl": ".",

        // other options go here

        "typeRoots": [
            "./node_modules/@types",
            "./typings"
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

完成此操作后,创建typings/vue相对于tsconfig.json您提到的路径的文件夹。在文件夹内typings/vue,创建index.d.ts文件。通常,您的声明文件如下所示:

import Vue from 'vue';
import { AppStore } from '../../src/store/store';

declare module 'vue/types/vue' {
    // Global properties can be declared
    // on the `VueConstructor` interface
    interface VueConstructor {
        // some more augmentation
    }

    // Properties added to Vue interface are added to Vue instance
    interface Vue {
        store$: AppStore;
    }
}
Run Code Online (Sandbox Code Playgroud)

与您尝试执行的方法相比,更喜欢这种方法,因为导入类型文件的扩展性不太好。

此外,使用最新的 Vue.js,您不需要node_modules/@types/vue声明。它们作为官方包装的一部分发货node_modules/vue。如果您这样做,那么您应该删除它们。