如何使用 es5 和 Visual Studio Code 获取外部 javascript 库的智能感知 [英] How to get intellisense for external javascript libraries with es5 and Visual Studio Code

查看:34
本文介绍了如何使用 es5 和 Visual Studio Code 获取外部 javascript 库的智能感知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理没有转译器的项目.当我想使用外部库并在 Visual Studio Code 中使用智能感知时,我需要使用导入(这不适用于 es5).

I am working with project without transpilers. When I want to use external library and use intellisense in Visual Studio Code I would need to use import (which would not work with es5).

示例:我想使用 axios 库,所以我用 npm 安装它,将脚本标记引用添加到 axios.js 并在 app.js 中编写应用程序代码.当我这样做时,我可以获得智能感知

Example: I want to use axios library so I install it with npm, add script tag reference to axios.js and write the application code in app.js. I can get intellisense when I do this

从 'axios' 导入 axios;

但是使用 es5 会失败.

but it would fail with es5.

我确实找到了一个 hacky 解决方法,它使我的智能感知在使用 es5 时不会失败:

I did find a hacky workaround that gives me intellisense would and not fail with es5:

var axios = axios ||require('axios').default;

但至少对我来说,这对于智能感知来说对我来说太难了:)

But at least for me this looks too hacky to me just for intellisense :)

我还注意到,例如 jquery intellisense 也可以在没有导入的情况下工作,并且认为原因是 jquery 类型定义文件不使用模块语法(导出)并且将事物添加到全局范围内.所以我也想知道是否有可能创建我自己的类型定义文件以将内容添加到全局范围内?

I also noticed that for example jquery intellisense also works without import and think the reason is that jquery type definition file does not use module syntax (export) and things are added into global scope. So I am also wondering would it be somehow possible to create my own type definition file to add things into global scope?

推荐答案

进一步调查,发现确实可以创建自己的辅助类型定义文件,该文件会将模块中的类型导入全局范围,以便在一个具有全球范围的 ES5 项目:

Investigated this further and found out that indeed you can just create your own helper type definition file that will import types in module into global scope in order to use this in a ES5 project with global scope:

在您的项目中创建文件 global.d.ts(名称无关紧要),内容如下:

Create file global.d.ts (name does not matter) in your project with following contents:

import { AxiosStatic } from "axios";

declare global {
  const axios: AxiosStatic;
}

这将使智能感知在全局上下文中工作(在我的 app.js 中)而无需使用导入.当然只有当你真的不能使用模块时才这样做(全局不好:))

That wil make intellisense work in global context (in my app.js) without having to use import. Of course only do this when you really can not use modules (global is bad :))

我会看看我是否能说服 vscode 的人(他们用这个文本编辑器做的非常好:))这也可能是 vscode 文档的有用补充(https://github.com/Microsoft/vscode/issues/63494)

I'll see if I can convince vscode people (who are imho doing excellent job with this text editor :)) that this might be useful addition to the vscode documentation as well (https://github.com/Microsoft/vscode/issues/63494)

这篇关于如何使用 es5 和 Visual Studio Code 获取外部 javascript 库的智能感知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆