在VSCode中声明一个Javascript全局命名空间对象。

15 浏览
0 Comments

在VSCode中声明一个Javascript全局命名空间对象。

我有一个新的Javascript环境,而不是Node.js或浏览器,并且它有一个新的全局对象GameGlobal,类似于Node.js中的global或浏览器中的window。因此,如果我将属性分配给GameGlobal(例如GameGlobal.THREE = 3),则可以在任何模块中使用该属性(通过THREE而不是GameGlobal.THREE)。不幸的是,VSCode无法识别它。

在上面的示例中,即使GameGlobal.THREE = require('three'),但@param {THREE.Intersection}中的THREEIntersection的工具提示都显示为“any”。我还参考了在.d.ts之外定义全局变量,但它没有起作用。

因此,我是否有办法自定义并添加一个名为GameGlobal的全局命名空间对象,以供VS Code IntelliSense使用?我相信关键可能是提供一个.d.ts文件。

我在VSCode中创建并打开了一个单独的js文件,然后使用了下面的代码。它给我提供了以下的工具提示:

if ('object' == typeof global) {
    //在Node.js环境中
    //工具提示显示为“any”,然后是'module global'。我认为这在node.js中是有效的。
} else if ('object' == typeof window) {
    //在浏览器环境中
    //工具提示显示为“var window: Window & typeof globalThis”。我认为这在浏览器中是有效的。
}
if ('object' == typeof globalThis) {
    //在浏览器环境中
    //工具提示上的`globalThis`显示为“module globalThis”
}
global.GameGlobal = global;
//window.GameGlobal = window;
GameGlobal.THREE = {
    Vector2: { x: 0, y: 0 }
};
THREE //工具提示显示为“any”
console.log('THREE:', THREE.Vector2.x); //THREE: 0

阅读完在TypeScript中使用globalThis之后,我写了一个global.d.ts文件。

// 
// 
// @typedef {GameGlobal.THREE} THREE GameGlobal.THREE: typeof require('three')
declare global {
    var GameGlobal: global;
}
//declare let GameGlobal = global & Window & typeof globalThis;
//declare var GameGlobal: Object;
declare var THREE: typeof import('three');
/**
 * contains basic information about a physical font. All sizes are specified in
 * logical units; that is, they depend on the current mapping mode of the display context.
 */
declare class TextMetric {
    /**
     * Is a `double` giving the calculated width of a segment of inline text in CSS pixels.
     * It takes into account the current font of the context.
     */
    width: number;
    height: number;
}
/**
 * Measures the dimensions of a piece of text in the canvas.
 * @param {CanvasRenderingContext2D} context
 * @param {string} text The text `String` to measure.
 * @return {TextMetric} A `TextMetric` object
 * @see https://stackoverflow.com/questions/1134586/how-can-you-find-the-height-of-text-on-an-html-canvas
 */
declare function measureText(context: CanvasRenderingContext2D, text: string): TextMetric;

我发现只有在使用import THREE from 'three'时,VSCode才能在代码THREE.Vector2和注释@param {THREE.Vector2}上显示正确的工具提示,但这不是我预期的结果。

  • window上公开全局声明
  • 根作用域类型
  • Node.js v13.9.0文档:全局对象

    这些对象在所有模块中都可用。

    这里列出的对象特定于Node.js。还有一些内置对象是JavaScript语言本身的一部分,也是全局可访问的。

    global

    添加于:v0.1.27

    • 全局命名空间对象。

      在浏览器中,顶级作用域是全局作用域。这意味着在浏览器中,var something将定义一个新的全局变量。在Node.js中,情况不同。var something在Node.js模块内部将局部于该模块。

  • MDN:标准内置对象

    这里的“全局对象”(或标准内置对象)一词并不是与全局对象混淆。在这里,“全局对象”指的是全局范围内的对象

    全局对象本身可以使用全局范围内的this运算符访问。实际上,全局范围包括全局对象的属性,包括任何继承的属性。

  • minigame-api-typings
0