Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)

目的:为了提高开发效率,在VScode我们可以使用 用户代码片段 来快速生成模板。

用处:用户代码片段其实类似于 webStorm 或者IDEA 的编辑器模板,输入某些名称即可快速生成代码model。

使用用法(mac os示例):

1. 打开配置文件

A. 用 command+shift+p 快捷键打开, 输入 snippet ,选择下图选项:首选项:配置用户代码片段。 (或者直接选择左上角的 Code => 首选项 => 用户代码片段)
Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)
B. 然后会弹出如下所示的框,我选择了javascriptreact语言。
Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)
C. 点击完生成如下所示的json文件
Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)

2.配置文件

A.配置文件是一个json文件:主要包含了一下几个参数配置:

prefix      :这个参数是使用代码段的快捷入口,比如这里的rnpage,在使用时输入rnpage会有智能感知.
body        :这个是代码段的主体.需要设置的代码放在这里,字符串间换行的话使用\r\n换行符隔开.注意如果值里包含特殊字符需要进行转义.
        多行语句的以,隔开
$1          :这个为光标的所在位置.
$2          :使用这个参数后会光标的下一位置将会另起一行,按tab键可进行$1到$2的快速切换,还可以有$3,$4,$5.....
description :代码段描述,在使用智能感知时的描述

B. 配置例子开始:rnpage模板

{
	// Place your snippets for javascriptreact here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	"rnpage": {
		"prefix": "rnpage",
		"body": [
			"import React from 'react'",
			"import { View, Text, StyleSheet } from 'react-native'",
			"import { RNPage, observer } from 'rn-framework';",
			"",
			"@observer",
			"class ${1:NAME} extends RNPage {",
			"    static navigation = {",
			"        title: '${2:Title}'",
			"    };",
			"",
			"    constructor (props) {",
			"        super(props);",
			"    }",
			"",
			"    componentWillMount () {",
			"        $3",
			"    }",
			"",
			"    render () {",
			"        return (",
			"            <View>",
			"                <Text>${4:文字}</Text>",
			"            </View>",
			"        )",
			"    }",
			"",
			"}",
			"",
			"export default ${5:NAME}"
		],
		"description": "RN page initial"
	}
}

Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)
C. 点击保存即可完成配置。

3. 使用模板

A. 新建一个类型为javascript react的文件,上面json文件的名称类型对应。
Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)
2.输入rnpage,弹出代码片段名称,点击选中,即可进行编辑(注意定义过$的地方tab键可以快速切换哦!)
Visual Studio Code 添加设置代码段(snippet)的使用(example: react native)