蓝色天空网mbsky.com · 知识 · 实践 · 创造VS Code · 本地阅读预览
教程 / DevOps / 工程化 / VS Code

VSCode 编写代码

通过创建并编写 app.js 体验 VS Code 内置的 JavaScript 语法高亮、IntelliSense 自动补全以及 Code Actions(灯泡快捷重构为模板字符串)功能。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

内置语言支持与创建 app.js

VS Code 原生内置了对 JavaScript、TypeScript、HTML 与 CSS 等前端核心语言的编辑支持,无需额外插件即可直接编码;其他语言(例如 Python)则会在后续章节通过安装官方扩展补齐完整智能感知。

在资源管理器(Explorer)视图中新建 `app.js`,写入定义 `sayHello(name)` 并调用 `console.log('Hello, ' + name)` 的示例脚本。输入过程中,VS Code 会自动弹出 IntelliSense 代码补全候选框(使用方向键 `↑`/`↓` 选择并按 `Tab` 键插入),同时通过语法高亮以不同色彩区分关键字、函数名与字符串字面量,提升代码可读性。

使用代码操作(Code Actions)重构为模板字符串

将光标停留在字符串 `'Hello,'` 上时,行首会浮现黄色小灯泡图标,提示当前位置存在可应用的快速修复或重构项(Code Action)。点击灯泡图标(或使用快捷菜单触发,注:macOS 通用触发 Code Action 为 `⌘.` / 补全建议为 `⌃Space`),选择 `Convert to template string(转换为模板字符串)`。

应用该代码操作后,原有的字符串拼接表达式 `"Hello, " + name` 会被自动重构为 JavaScript ES6 模板字符串 `` `Hello, ${name}` ``。模板字符串允许直接在反引号内嵌入 `${表达式}`,写法更简洁且避免繁琐加号拼接。本站离线脚本已对 `app.js` 词法分析、IntelliSense 补全过滤与模板字符串自动重构进行了确定性验证。

运行 app.js 词法高亮分析、IntelliSense 补全与模板字符串 Code Action 重构离线校验

python · 阅读源码
"""Offline VS Code JS editing, IntelliSense tokenization & Code Action refactor verifier for Ch14."""
import json
import re

VERSION = "CPython 3.12.14 offline VS Code JS IntelliSense & Code Action verifier"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def convert_concat_to_template(expr: str) -> str:
    m = re.fullmatch(r"""\s*(['"])(.*?)\1\s*\+\s*([A-Za-z_$][\w$]*)\s*""", expr)
    if not m:
        return expr
    prefix_text, ident = m.group(2), m.group(3)
    return f"`{prefix_text}${{{ident}}}`"


def main():
    cases = []

    app_js = (
        "function sayHello(name) {\n"
        "  console.log('Hello, ' + name);\n"
        "}\n\n"
        "sayHello('VS Code');\n"
    )
    js_keywords = {"function", "return", "const", "let", "var"}
    tokens = re.findall(r"[A-Za-z_$][\w$]*|'[^']*'", app_js)
    found_keywords = [t for t in tokens if t in js_keywords]
    completions = [s for s in ["console", "const", "continue", "confirm"] if s.startswith("con")]
    cases.append(
        check(
            "js_intellisense_and_syntax_tokens",
            "Verify app.js syntax tokenization and IntelliSense prefix suggestion ranking",
            {
                "keywords": ["function"],
                "contains_console_log": True,
                "string_literals": ["'Hello, '", "'VS Code'"],
                "top_completion_for_con": "console",
            },
            {
                "keywords": found_keywords,
                "contains_console_log": "console.log" in app_js,
                "string_literals": [t for t in tokens if t.startswith("'")],
                "top_completion_for_con": completions[0],
            },
        )
    )

    # Case 2: Code Action "Convert to template string" refactor
    expr_double = '"Hello, " + name'
    expr_single = "'Hello, ' + name"
    refactored_double = convert_concat_to_template(expr_double)
    refactored_single = convert_concat_to_template(expr_single)
    transformed_js = app_js.replace(expr_single, refactored_single)
    cases.append(
        check(
            "code_action_template_string_refactor",
            "Verify Code Action refactoring of string concatenation into ES6 template literal",
            {
                "double_quote_refactor": "`Hello, ${name}`",
                "single_quote_refactor": "`Hello, ${name}`",
                "transformed_contains_template": True,
                "eval_preview": "Hello, VS Code",
            },
            {
                "double_quote_refactor": refactored_double,
                "single_quote_refactor": refactored_single,
                "transformed_contains_template": "console.log(`Hello, ${name}`);" in transformed_js,
                "eval_preview": "Hello, " + "VS Code",
            },
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 app.js 关键字与字符串词法单元、`con` 补全候选排序以及将字符串拼接转换为 `Hello, ${name}` 模板字面量的重构结果。
运行 app.js 词法高亮分析、IntelliSense 补全与模板字符串 Code Action 重构离线校验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:46530f3dfb80e77730e7bcb3697fe9fd45538118f541000f51aa87db2cacb2db

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载VSCode 编写代码实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:035a1f9799e9c922f914f98a24cafea803454b51349a70cfa77f881fa20387a3

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 VS Code 编辑器中看到光标所在行出现小灯泡图标(Code Action)代表什么?将 `'Hello, ' + name` 转为模板字符串后有什么好处?

展开参考解答

小灯泡代表语言服务提供了可一键应用的快速修复或重构建议;转为 `` `Hello, ${name}` `` 后可直接内嵌表达式、减少引号与加号拼接错误并提高多变量插值可读性。

规范与官方依据