如何为TSC提供URI导入的打字稿定义? [英] How do I provide TSC with typescript definitions for URI imports?
问题描述
import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js'
如果我要求TSC编译以上内容,它会抱怨(合理地如此)无法找到该模块的定义。但是,我不知道如何给TypeScript定义文件。 声明模块'https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js'{...}
不工作,并且 https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js
无效,因此我可以不要创建一个名为该文件的文件。我尝试使用 tsconfig.json
路径
,但也无法正常工作。
If I ask TSC to compile the above it complains (reasonably so) about not being able to find definitions for that module. However, I can not figure out how to give TypeScript the definition file. declare module 'https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js' { ... }
doesn't work, and https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js
isn't a valid filename so I can't create a file named that. I tried using tsconfig.json
paths
, but couldn't get that to work either.
使TypeScript接受我的Vue类型定义需要什么魔术?
What is the magic required to get TypeScript to accept my Vue type definitions?
注意:理想的解决方案适用于 // cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js
和 ./ vue.esm.js
和 ./ vue.js
。后两个是相对路径,我不知道如何为它提供定义路径。
Note: An ideal solution would work with //cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js
and ./vue.esm.js
and ./vue.js
as well. The latter two are relative paths which I can't figure out how to provide a definition path for.
推荐答案
您在问什么为此:
stubs.d.ts
stubs.d.ts
declare module 'https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.esm.js' {
const Vue: typeof import ('vue');
export default Vue;
}
但是,使用import语句从CDN加载模块并不是使用模块的惯用方式—至少我不知道,没有捆绑软件支持。
However, using an import statement to load a module from a CDN is not an idiomatic way to use modules — and no bundler supports that, at least not to my knowledge.
如果您想将Vue用作模块,应将其安装在本地( npm install vue
),然后从本地 node_modules
目录导入。
If you want to use Vue as a module, it should be installed locally (npm install vue
) and then imported from your local node_modules
directory.
import Vue from 'vue';
如果您想将其用作UMD软件包(即,使浏览器从CDN,而不是捆绑包中的CDN,那么您需要安装类型并将其包含在项目中。
If you want to use it as a UMD package (that is, make the browser download it from a CDN rather than from your bundle), then you need to install the typings and include them in your project.
Vue捆绑其声明文件( * .d.ts
)放在实际可执行代码旁边,因此您不能仅安装类型。您仍然需要下载整个软件包。
Vue bundles its declaration files (*.d.ts
) next to the actual executable code, so you cannot install just types. You need to download the entire package anyway.
npm install vue
将已安装的类型定义添加到项目中。在您的 tsconfig.json
中,确保 vue
包含在 compilerOptions.types
。
Add the installed type definitions to your project. In your tsconfig.json
, make sure "vue"
is included in compilerOptions.types
.
{
"compilerOptions": {
"types": ["vue"]
}
}
这将在内部公开全局类型您的脚本。
This will expose the typings globally inside your scripts.
这篇关于如何为TSC提供URI导入的打字稿定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!