英文:
Add TypeScript support to vue.global.prod.js
问题
由于我们的设置,我们使用 Vue 的 vue.global.prod.js
构建,并全局访问 Vue 方法,例如 const app = window.Vue.createApp
和 window.Vue.ref(false)
。我想知道是否可以通过我们的 index.d.ts
文件添加支持,以便 TypeScript 可以识别所有 window.Vue
方法?
英文:
Due to our setup, we use the vue.global.prod.js
build of Vue and access Vue methods globally such as const app = window.Vue.createApp
and window.Vue.ref(false)
. I'm wondering if it's possible to add support via our index.d.ts
file so all the window.Vue
methods are recognised by TypeScript?
答案1
得分: 1
Vue并未提供其类型作为独立的包([@types/vue](https://www.npmjs.com/package/@types/vue) 已经在很久以前被弃用)。但你可以在声明文件中导入其类型,并将它们分配给全局的 `Window` 接口:
将这段代码放在一个名为 `vue-shim.d.ts` 的文件中,放在 `src` 文件夹中<sup>***1, 2***</sup>:
```ts
import Vue from 'vue'
declare global {
interface Window { Vue: typeof Vue }
}
现在你可以在任何 TypeScript 片段中使用类似以下的代码:
const { createApp, ref } = window.Vue
// 使用 `createApp` 和 `ref`,它们已被类型化
<sup>1</sup> - 为了使其工作,你需要在项目中安装 vue
,但只需要安装其类型(TypeScript 需要从某处读取它们,对吧?)。但你不会在任何地方导入 vue
(除了上面的声明文件,它不包含在运行时代码中)。
<sup>2</sup> - Vue
将根据安装的版本(在 package.json
中)在你的项目中获得类型,这可能会与从 CDN 导入的版本不同。它们需要保持同步,以便向前进行。
<details>
<summary>英文:</summary>
Vue does not provide its types as a stand-alone package ([@types/vue](https://www.npmjs.com/package/@types/vue) has been deprecated a long time ago). But you can import its typings inside a declaration file and assign them to the global `Window` interface:
Place this code inside a `vue-shim.d.ts`, in `src` folder <sup>***1, 2***</sup>:
```ts
import Vue from 'vue'
declare global {
interface Window { Vue: typeof Vue }
}
Now you can use something along these lines in any TypeScript fragment:
const { createApp, ref } = window.Vue
// use `createApp` and `ref`, they're typed
<sup>1</sup> - for this to work you need vue
installed in the project, but only for its types (TypeScript needs to read them from somewhere, right?). But you won't be importing vue
anywhere (other than the above declaration file, which is not included in runtime code).
<sup>2</sup> - Vue
will be typed in your project according to the installed version (in package.json
), which might end up being different than the one imported from the cdn. They need to be kept in sync, going forward.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论