使用 create-vue 找不到模块“vuex”的声明文件

Hor*_*her 6 typescript eslint vue.js vuex vuejs3

我正在尝试使用 Vue3 和 typescript 初始化一个项目,但是将 vuex 添加到项目后,它不会\xc2\xb4t 编译。

\n

我做了什么:

\n
    \n
  1. 首先,我使用 create-vue 使用推荐选项创建了项目:
  2. \n
\n

创建Vue项目

\n
    \n
  1. 安装的vuex:
  2. \n
\n
npm install vuex@next --save\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 按照 Vuex 文档中的步骤操作:Typescript 支持
  2. \n
\n

因此,在我的简单存储文件中,我有:

\n
import { type InjectionKey } from \'vue\'\nimport { createStore, Store } from \'vuex\'\n\n// define your typings for the store state\nexport interface State {\n  count: number\n}\n\n// define injection key\nexport const key: InjectionKey<Store<State>> = Symbol()\n\nexport const store = createStore<State>({\n  state: {\n    count: 0\n  }\n})\n
Run Code Online (Sandbox Code Playgroud)\n

但如果我运行npm run build,这就是结果:

\n
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.\n  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.\n\n2 import { createStore, Store } from \'vuex\'\n
Run Code Online (Sandbox Code Playgroud)\n

看起来它已经找到了 vuex 类型,但无论如何都无法导入。我该如何解决这个问题?

\n

我已经vuex.d.ts在 vuex 文档之后添加了一个 。

\n
import { Store } from \'vuex\'\n\ndeclare module \'@vue/runtime-core\' {\n  // declare your own store states\n  interface State {\n    count: number\n  }\n\n  // provide typings for `this.$store`\n  interface ComponentCustomProperties {\n    $store: Store<State>\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

mas*_*a03 15

这似乎是由相对较新版本的 typescript 的更改引起的,该版本不再识别 vuex 类型定义。

解决方法1

将以下代码保存在适当的目录下,名称如vuex.d.ts. 这应该允许 TypeScript 正确识别 vuex 模块。

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";
}
Run Code Online (Sandbox Code Playgroud)

解决方法2

我还没有证实这一点,但使用稍旧版本的打字稿可能会解决问题。

  • 解决方法 1 对我有用。谢谢 (4认同)