我们项目中的页面(主要是后台系统)功能大多类似,每次新增的时候,会写很多相似的代码。所以利用一个可配置的模板来生成文件代码是一个可以提高效率的方式。在网上找了下现有的vscode插件,发现都比较轻量(如Simple React Snippets),所以就自己写了一个偏定制化的配置。
配置vscode snippets
首先
- 打开VSCode,按下快捷键组合shift+command+p呼出控制台
- 在控制台输入:
- 选择 typescript react 配置(若是vue或者js也可以选对应的,或是新增一个snippet)
即可进入 typescriptreact.json文件,将下面的内容覆盖到文件中(此配置可以根据自身需求,灵活修改, body中即为复用的代码,prefix即为快捷键)
{
// Place your snippets for typescriptreact 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:
"Function Component": {
"prefix": "index.tsx",
"body": [
"import { useRef, useState } from 'react';",
"import ListContent from '@kant/list-content';",
"import { TableQueryActions } from '@kant/hooks/lib/useTableQuery';",
"import api from '@/services';",
"import { searchFields, tableFields } from './fields';",
"",
"enum AUTH_CODE {",
"XX = 'xx',",
"}",
"const $1: AuthComponent = () => {",
"const listContentRef = useRef<TableQueryActions>(null);",
"const [tableDataProps, setTableDataProps] = useState({",
"data: [],",
"total: 0,",
"});",
"",
"const fetchData = async (params) => {",
"const { records: data, total } = await api.getDidPages({",
"...params,",
"sort: ['modifyTime__DESC'],",
"});",
"setTableDataProps({ data, total });",
"};",
"",
"const listContentProps = {",
"formProps: {",
"fields: searchFields,",
"},",
"tableProps: {",
"fields: tableFields,",
"rowKey: 'id',",
"nextFields: [",
"{",
"key: 'action',",
"props: (_, record) => {",
"return {",
"options: [",
"{",
"name: 'xx',",
"onClick() {",
"},",
"code: AUTH_CODE.xx,",
"},",
"],",
"};",
"},",
"},",
"],",
"...tableDataProps,",
"},",
"fetchData,",
"ref: listContentRef,",
"};",
"",
"return (",
"<>",
"<ListContent {...listContentProps} />",
"</>",
");",
"};",
"",
"$1.authConfig = {",
"name: 'xx',",
"actions: [{ name: 'xx', code: AUTH_CODE.xx }],",
"};",
"",
"export default $1;",
""
],
"description": "Function Component With Table And Form",
},
"Form Fields": {
"prefix": "fields.tsx",
"body": [
"export const searchFields = [",
"{",
"name: 'campaignID',",
"key: 'campaignId',",
"},",
"];",
"export const tableFields = [",
"{",
"name: 'campaignID',",
"key: 'campaignId',",
"width: 200,",
"},",
"{",
"name: '操作',",
"key: 'action',",
"type: 'action',",
"width: 120,",
"fixed: 'right' as FixedPosition,",
"},",
"];",
],
"description": "Create fields.tsx",
}
}
实现效果
上述操作配置好之后,即可快速利用模板生成文件了
操作步骤:
- 新增一个index.tsx
- 输入index.tsx
- 按下tab 或者enter键 即可生成模板代码
生成之后,有一个默认的作为组件Name的占位符,输入Page之后默认填充,效果如下
- 除了index.tsx之外还支持fields.tsx,效果如下
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。