VSCode 代码片段
2026/7/27...大约 1 分钟
VSCode 代码片段 (Snippets)
VSCode 提供 Snippet 功能,让常用代码模板通过简短前缀展开为完整代码块。
配置位置
- 全局:
Code → Preferences → Configure User Snippets - 按语言:
{language}.json(如cpp.json、python.json)
示例:ROS2 C++ Publisher Snippet
{
"ROS2 C++ Publisher": {
"prefix": "ros2pub",
"body": [
"#include \"rclcpp/rclcpp.hpp\"",
"#include \"std_msgs/msg/${1:string}.hpp\"",
"",
"class ${2:NodeName} : public rclcpp::Node {",
"public:",
" ${2:NodeName}() : Node(\"${3:node_name}\") {",
" publisher_ = this->create_publisher<std_msgs::msg::${1:string}>(\"${4:topic}\", 10);",
" timer_ = this->create_wall_timer(",
" std::chrono::milliseconds(${5:500}),",
" [this]() { auto msg = std_msgs::msg::${1:string}(); publisher_->publish(msg); });",
" }",
"private:",
" rclcpp::Publisher<std_msgs::msg::${1:string}>::SharedPtr publisher_;",
" rclcpp::TimerBase::SharedPtr timer_;",
"};"
],
"description": "Create a ROS2 C++ Publisher node"
}
}关键字段
prefix:触发关键字(输入ros2pub+ Tab 触发)body:模板内容,多行用数组description:在补全列表里的描述${1:default}:占位符,数字定义 Tab 跳转顺序,:后是默认值
进阶
- 多个同位置占位符:所有
${1:topic}会同步编辑 - 嵌套占位符:
${1:${2:default}} - 变量:
$TM_FILENAME_BASE、$CURRENT_YEAR等
适用场景
- 反复写的 boilerplate(ROS2 节点、类定义、测试模板)
- 团队内统一代码风格
- 减少重复输入 + 拼写错误
相关
- [[../sources/Coding_Skill.md]] — 编码技术知识域摘要
- [[../entities/ROS2.md]] — ROS2 实体
