简体   繁体   English

在vscode JavaScript中设置全局声明

[英]Set global declaration in vscode JavaScript

I'm working on a JavaScript transpiler that apart from other things will also replace certain functions and variables upon build. 我正在开发一个JavaScript转换器,除了其他东西之外,它还会在构建时替换某些函数和变量。

For example the following file ( ./src/my-module.js ): 例如,以下文件( ./src/my-module.js ):

defineModule("MyModule", function(exports) {
  return exports;
});

Will be copied and converted to ( ./build/my-module.js ): 将被复制并转换为( ./build/my-module.js ):

(function(global, factory) {
  "use strict";
  if (typeof exports !== "undefined" && typeof module !== "undefined") module.exports.MyModule = factory(exports.MyModule || {});
  else factory(global.MyModule = {});
})(this, function(exports) {
  return exports;
});

Some of these functions could also return a result. 其中一些功能也可以返回结果。 In that case I would like to be able to declare the types of the parameters and the result of the function without using require . 在这种情况下,我希望能够在不使用require情况下声明参数的类型和函数的结果。 Is it possible to have a global .d.ts definition in VSCode? 是否可以在VSCode中使用全局.d.ts定义?

So far, all I've done is add the functions to the global variable of eslint so as to not have errors. 到目前为止,我所做的只是将函数添加到eslint的全局变量中,以便没有错误。

You can specify your own TypeScript folder path in your settings.json where you can specify your own lib.*.d.ts files using the typescript.tsdk option. 您可以指定你自己的打字稿文件夹路径settings.json在那里你可以指定自己的lib.*.d.ts使用文件typescript.tsdk选项。

{
  "typescript.tsdk": "node_modules/typescript/lib"
}

Acknowledgment 承认

This answer was mostly inspired by mootrichard's answer , but since it had to be modified, to work with my project, I am also adding this answer. 这个答案主要是受到mootrichard的回答的启发,但由于必须对其进行修改,以便与我的项目合作,我也在补充这个答案。

Solution

If you press F12 on a global JavaScript function (ie eval ) a typing declarations file will appear ( lib.es5.d.ts ), containing JavaScript documentation. 如果在全局JavaScript函数(即eval )上按F12 ,将出现一个包含JavaScript文档的输入声明文件( lib.es5.d.ts )。 You can just add any extra namespaces or function to that file. 您只需将任何额外的命名空间或函数添加到该文件即可。 But you need to use declare and not export . 但是你需要使用declare而不是export

Example: 例:

//... Other Global JavaScript Declarations

// JavaScript Number Interface
interface Number {
  //...
}

// JavaScript Date Interface
interface Date {
  //...
}

declare function ezDefine(moduleName: string, generator: *): void;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM