日常开发中经常需要创建react组件:
新建组件目录->新建index.tsx->写组件的初始代码
这些步骤都是重复性的,所以开发了这个vscode拓展,节省不必要的时间,优化开发体验。
使用方法
右击目标目录,根据不同的参数生成不同的内容的代码,传参规则(暂时支持):组件名,ts,less。
只传组件名的时候生成的代码:
import React from '@alipay/bigfish/react';
const Test = () => {
return <></>
};
export default Test;
传组件名,ts时:
import React from '@alipay/bigfish/react';
import type { FC } from '@alipay/bigfish/react';
interface Props {
};
const Test: FC<Props> = () => {
return <></>
};
export default Test;
传组件名,ts,less时:
import React from '@alipay/bigfish/react';
import type { FC } from '@alipay/bigfish/react';
import styles from './index.less';
interface Props {
};
const Test: FC<Props> = () => {
return <></>
};
export default Test;
组件名必选写在第一位,后面的参数用,分割,根据这个规则还可以制定更多的模板。
拓展开发
配置package.json,非常的简单:
"activationEvents": [
"onCommand:react-component.creat"
],
"contributes": {
"commands": [
{
"command": "react-component.creat",
"title": "新建React组件"
}
],
"menus": {
"explorer/context": [
{
"command": "react-component.creat",
"group": "navigation"
}
]
}
},
主要代码逻辑:
const vscode = require('vscode');
const fs = require('fs');
const getFileContext = (params) => {
const [name,...restParams] = params;
const hasTs = restParams.includes('ts');
const hasLess = restParams.includes('less');
const template = [
`import React from '@alipay/bigfish/react';`,
`${ hasTs ? `\nimport type { FC } from '@alipay/bigfish/react';` : `` }`,
`${ hasLess ? `\nimport styles from './index.less';` : `` }`,
`${ hasTs ? `\n
interface Props {
};` : `` }`,
`\n
const ${name}${ hasTs ? `: FC<Props>` : `` } = () => {
return <></>
};`,
`\n
export default ${name};`
]
return `${template.filter(d=>d).join('')}`;
}
function activate(context) {
let disposable = vscode.commands.registerCommand('react-component.creat', function (url) {
let uri = url.fsPath;
vscode.window.showInputBox({ placeHolder: '请输入组件名称' }).then((inputValue) => {
if (inputValue) {
const params = inputValue.split(',');
const [componentName,...restParams] = params;
fs.mkdir(`${uri}/${componentName}`, function (err) {
if (!err) {
const indexUrl = `${uri}/${componentName}/index.tsx`;
fs.writeFile(indexUrl, getFileContext(params), function (err) {
if (err) {
vscode.window.showErrorMessage(err.message);
} else {
vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.file(indexUrl))
}
});
if( restParams.includes('less') ){
const lessUrl = `${uri}/${componentName}/index.less`;
fs.writeFile(lessUrl, ``, function (err) {
if (err) {
vscode.window.showErrorMessage(err.message);
}
});
}
} else {
vscode.window.showErrorMessage(err.message);
}
});
}
})
});
context.subscriptions.push(disposable);
}
function deactivate() { }
module.exports = {
activate,
deactivate
}