如何让VSCode Intellisense支持识别ServiceNow Script Include中的方法
VSCode ServiceNow扩展跨Script Include Intellisense识别异常问题
我一直在使用VSCode的ServiceNow扩展,虽然存在一些小问题,但整体而言完全符合我的使用需求。不过我在开发大型作用域应用时遇到了一个问题:Intellisense无法识别当前正在编辑的Script Include之外的其他Script Include中定义的函数等对象。
ServiceNow Script Include标准格式
var MyScriptInclude = Class.create(); MyScriptInclude.prototype = { initialize: function() { }, /** * Do nothing function for illustration purposes * @param {*} a * @param {string} b * @param {number} c */ fn_1: function(a, b, c) { }, fn_n: function(d, e) { }, type: 'MyScriptInclude' };
异常表现
如果我在Visual Studio Code中编写如下代码,当我尝试引用另一个Script Include的fn_1方法时,Intellisense不会加载任何相关信息,提示框中仅会显示any类型:
var MyOtherScriptInclude = Class.create(); MyOtherScriptInclude.prototype = { initialize: function() { }, doSomethingWithOther: function() { var my_first_script_include = new MyScriptInclude(); my_first_script_include.fn_1(); //<-- does not find any information about fn_1 }, type: 'MyOtherScriptInclude' };
问题成因
VSCode无法识别Class.create()的返回值。ServiceNow使用开箱即用的名为PrototypeServer的Script Include来“构建”用户编写的所有Script Include,其实现代码如下:
var Class = { create: function() { return function() { /* This anonymous function will execute in the scope of the caller in interpreted mode. The initalize method is a utility we provide for giving a hook into the creation of a script include in scope. Many global script includes do not have an initialize function, and therefore we should only call this.initialize when present. */ if (this.initialize) this.initialize.apply(this, arguments); }; } };
已尝试的无效解决方法
我尝试了多种方法来让Visual Studio Code关联Script Include中的类变量和其原型对象,均未生效:
- 给类变量添加文档注释,在prototype中使用lends注解:该方法在编译文档时可以正确关联类和原型,但对Intellisense完全没有作用,代码示例如下:
/** * My do nothing class for illustration purposes * @class */ var MyScriptInclude = Class.create(); MyScriptInclude.prototype = { /** @lends MyScriptInclude.prototype */ /** * @constructs */ initialize: function() { } //... };
- 将lends注解放在prototype外部:无效果,代码示例如下:
/** @lends MyScriptInclude.prototype */ MyScriptInclude.prototype = {};
- 显式将类变量定义为函数类型:无效果,代码示例如下:
/** * My do nothing class for illustration purposes * @type {function} */ var MyScriptInclude = Class.create(); MyScriptInclude.prototype = { };
- 导入PrototypeServer全局Script Include到工作区:此时VSCode可以正确识别
Class.create()函数、显示其相关信息并将类变量识别为函数,但类变量和原型方法之间仍然没有关联,Intellisense依旧将原型中的所有方法识别为any类型,也无法查找定义。
这个问题并不会完全阻碍开发,毕竟在VSCode中开发的效率远高于在ServiceNow实例中开发,但如果能找到解决方案,开发体验会好很多。
内容的提问来源于stack exchange,提问作者JChapman15
相关产品推荐
相关产品推荐

