在VS Code中如何查看外部引入对象的悬停值?
问题:VS Code悬停导入的JavaScript对象时无法显示其值?
我正在做Cypress自动化测试,当前问题主要和JavaScript、VS Code相关。
我在一个文件中导出了如下对象:
const ui = { profile:{ details:{ firstName: "#collapse1 input[placeholder='First Name']" } } } module.exports = ui;
在测试项目里我这样引入该文件:
const ui = require("../../../support/locators.js"); // 现在用引入的UI对象调用Cypress的get方法 cy.get(ui.profile.details.firstName).click(); // 我之前的写法 const LASTNAME_SELECTOR = "#collapse1 input[placeholder='Last Name']"; cy.get(LASTNAME_SELECTOR).click();
这种对象嵌套的写法在编码结构上更优,但对比之前同文件定义常量的写法,存在一个问题:导入对象后,无法像悬停常量那样直接查看对象属性的具体值。
有没有特定的导入方式,能让VS Code在悬停对象属性时显示对应的值?
可行的解决方法
1. 切换为ES模块的export/import语法
将导出文件改为ES模块格式:
export const ui = { profile:{ details:{ firstName: "#collapse1 input[placeholder='First Name']" } } };
测试文件中使用import引入:
import { ui } from "../../../support/locators.js";
VS Code对ES模块的类型推断和值预览支持更完善,悬停ui.profile.details.firstName时即可看到对应的选择器值。
2. 为对象添加JSDoc注释
如果不想更改模块系统,给导出的对象添加JSDoc类型注释,帮助VS Code识别属性值:
/** * @type {{ * profile: { * details: { * firstName: string * } * } * }} */ const ui = { profile:{ details:{ firstName: "#collapse1 input[placeholder='First Name']" } } } module.exports = ui;
这种方式无需修改导入语法,VS Code会根据注释解析出属性的具体值,悬停时正常显示。
3. 使用TypeScript类型定义(进阶方案)
如果项目支持引入TypeScript,直接为对象定义接口类型,既能实现悬停预览,还能获得类型检查能力:
interface UILocators { profile: { details: { firstName: string; }; }; } const ui: UILocators = { profile:{ details:{ firstName: "#collapse1 input[placeholder='First Name']" } } }; export default ui;
测试文件引入后,悬停属性即可看到对应的值,同时还能避免属性拼写错误。
内容的提问来源于stack exchange,提问作者samantha
相关产品推荐
相关产品推荐

