I am trying to initalize a project with Vue3 and typescript, but after adding vuex to the project, it won´t compile.
What I did:
npm install vuex@next --save
So, in my simple store file I have:
import { type InjectionKey } from 'vue'
import { createStore, Store } from 'vuex'
// define your typings for the store state
export interface State {
count: number
}
// define injection key
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
count: 0
}
})
But if I run npm run build
, this is the result:
src/stores/index.ts:2:36 - error TS7016: Could not find a declaration file for module 'vuex'. '/home/user/projects/vue_projects/init-test/node_modules/vuex/dist/vuex.mjs' implicitly has an 'any' type.
There are types at '/home/user/projects/vue_projects/init-test/node_modules/vuex/types/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'vuex' library may need to update its package.json or typings.
2 import { createStore, Store } from 'vuex'
It seems that it has found vuex types, but could not import anyway. How do I solve that?
I already added a vuex.d.ts
, following the vuex docs.
import { Store } from 'vuex'
declare module '@vue/runtime-core' {
// declare your own store states
interface State {
count: number
}
// provide typings for `this.$store`
interface ComponentCustomProperties {
$store: Store<State>
}
}
It appears to be caused by a change in a relatively new version of typescript that no longer recognizes vuex type definitions.
Save the following code under an appropriate directory with a name like vuex.d.ts
. This should allow TypeScript to correctly recognize the vuex module.
declare module "vuex" {
export * from "vuex/types/index.d.ts";
export * from "vuex/types/helpers.d.ts";
export * from "vuex/types/logger.d.ts";
export * from "vuex/types/vue.d.ts";
}
I have not confirmed this, but using a slightly older version of typescript may solve the problem.