我需要这样的东西。一旦我在项目中创建了一个文件夹。例如一个 React 项目。我可以选择该文件夹并运行某种宏或一系列可以执行此操作的操作。
前提是文件夹的名称是 Component
例如,当播放宏时,它会这样做:
创建一个名为 Component.js
的文件这将具有某种片段默认内容。
创建一个名为 Component.styled.js
的文件这又会在其中包含某种片段默认内容。
创建一个名为 index.js
的文件内容:export { default } from './Component'
其中 Component 实际上是文件夹的名称。
我不知道从哪里开始……我研究了宏,我知道如何使用 Visual Studio 代码用户片段,但不确定如何完成这个确切的事情。
最佳答案
使用名为 macro-commander 的宏扩展您可以相当容易地创建一个文件夹并包含文件(如果您愿意,可以使用一些默认内容)。但它看起来有点复杂,因为它本质上是在你的 settings.json 中编写一个扩展,但运行起来很顺利。安装扩展后,此代码将进入您的 settings.json:
"macros": {
"createReactFolderAndFiles" : [
{
"javascript": [
"const newReactFolder = await window.showInputBox()", // get the component's name
// create a object to store various edits, including file creation, deletion and edits
"const we = new vscode.WorkspaceEdit();",
// get the workspace folder path + file:/// uri scheme
"const thisWorkspace = vscode.workspace.workspaceFolders[0].uri.toString();", // file:///c:/Users/Mark/OneDrive/Test Bed
// append the new folder name
"const uriBase = `${thisWorkspace}/${newReactFolder}`;", // file:///c:/Users/Mark/OneDrive/Test Bed/Test
// "await window.showInformationMessage(` ${uriBase}`)", // just handy to check on progress
// create uri's for the three files to be created
"let newUri1 = vscode.Uri.parse(`${uriBase}/index.js`);",
"let newUri2 = vscode.Uri.parse(`${uriBase}/${newReactFolder}.js`);",
"let newUri3 = vscode.Uri.parse(`${uriBase}/${newReactFolder}.styled.js`);",
"let newFiles = [ newUri1, newUri2, newUri3];",
"for (const newFile of newFiles) { let document = await we.createFile(newFile, { ignoreIfExists: false, overwrite: true });};",
"let styledContent = `first line flush left", // how to use template literals in this macro
"second line will be flush left",
" third line indented`;",
// insert text into the top of each file
"await we.insert(newUri1, new vscode.Position(0, 0), `export { default } from './${newReactFolder}'`);",
"await we.insert(newUri2, new vscode.Position(0, 0), `my ${newReactFolder}.js content`);",
"await we.insert(newUri3, new vscode.Position(0, 0), styledContent);",
"await vscode.workspace.applyEdit(we);", // apply all the edits: file creation and adding text
"for (const newFile of newFiles) { let document = await vscode.workspace.openTextDocument(newFile); await document.save(); };",
]
}
]
},
它允许您在设置中使用 vscode 扩展 api。要运行此宏,请设置键绑定(bind):{
"key": "alt+j",
"command": "macros.createReactFolderAndFiles"
},
它会做的第一件事是弹出一个文件夹名称的输入框。输入一个,然后按 Enter。如果您有想要重复使用的默认内容,您可以存储并检索它以在此宏中使用。假设默认内容在同一个工作区
/templates/defaultComponent.txt
.这将获得该内容:
"let defaultContent = await vscode.workspace.fs.readFile(vscode.Uri.parse(`${thisWorkspace}/templates/defaultComponent.txt`));",
并将其添加到您的文件之一:"await we.insert(newUri3, new vscode.Position(0, 0), defaultContent.toString());",
正如您在演示中看到的那样,由于某种原因,它总是打开几个新创建的文件——我不知道如何防止这种情况发生。
虽然代码看起来很复杂,但我认为针对不同的文件名或内容修改它很简单。
关于visual-studio-code - 记录 'macro' ?还是 Visual Studio Code 中的一系列操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63980558/