Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Augmenting vue.js in typescript

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");

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
    }
}

But this:

var vm = new Vue()
console.log(vm.$myProperty);

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?

like image 971
Archeg Avatar asked May 06 '26 21:05

Archeg


1 Answers

Assuming your project has tsconfig.json, you should set following compilerOptions:

{
    "compilerOptions": {

        "baseUrl": ".",

        // other options go here

        "typeRoots": [
            "./node_modules/@types",
            "./typings"
        ]
    }
}

Once you do that, create typings/vue folder relative to tsconfig.json and the path you mentioned. Inside typings/vue folder, create index.d.ts file. Typically, your declaration file would look like:

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;
    }
}

Prefer this approach over the one that you are trying to do as importing type files doesn't scale really well.

Also, with latest Vue.js, you don't need node_modules/@types/vue declarations. They are shipped as part of official node_modules/vue package. If you are doing that then you should delete those.

like image 112
Harshal Patil Avatar answered May 08 '26 11:05

Harshal Patil