初始化项目
依赖下载
1,yo
2,generator-code
3,vsce
初始化项目
yo code
项目启动
vscode左侧菜单栏debug调试按钮,运行和调试选择Run EXTension进行运行
主要文件介绍
extension.js
代码入口文件,该文件有两个函数 activate 和deactivate,前者函数在插件安装时被调用,后者在插件卸载时被调用
package.json
项目配置文件,用来管理插件信息项目依赖等
具体的操作流程请参考
创建一个webview以及webview端与插件端的通信
这里只讲述我在工作中遇到的一些问题
1,webview端 根本统计特殊字段 且定位特殊字段在项目中的位置
const vscode = require('vscode');
function activate(context) {
let disposable = vscode.commands.registerCommand('extension.locateKeywordInVueProjects', () => {
const keyword = 'vue'; // 这里设置你想要搜索的关键词
vscode.workspace.findFiles('**/*.vue', null, 10000)
.then(vueFiles => {
vueFiles.forEach(fileUri => {
vscode.workspace.openTextDocument(fileUri).then(textDocument => {
if (textDocument.getText().includes(keyword)) {
vscode.window.showTextDocument(textDocument, 1, false).then(editor => {
const positions = getAllIndexes(textDocument.getText(), keyword);
positions.forEach(position => {
const start = new vscode.Position(0, position);
const end = new vscode.Position(0, position + keyword.length);
const range = new vscode.Range(start, end);
editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
editor.setDecorations(decorationType, [range]);
});
});
}
});
});
});
});
context.subscriptions.push(disposable);
}
function getAllIndexes(str, keyword) {
let indexes = [];
let start = 0;
while (true) {
let index = str.indexOf(keyword, start);
if (index === -1) {
break;
}
indexes.push(index);
start = index + keyword.length;
}
return indexes;
}
const decorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: 'yellow'
});
module.exports = {
activate
};
2,在webview端进行图片上传时,实际时是从前端获取到图片物理地址,将地址传给后端,后端通过地址读取图片信息,然后进行上传服务器的操作,从前端读取的图片信息无法通过web端和插件端的通信方式进行传递,后端在读取信息的时候需要注意:
1,后端获取到前端发来的图片物理地址时,不可以直接用fs.readFileSync()的方法读取,需要用fs.createReadStream(),因为通过readFileSync获取到的是一个图片的buffer,而接口参数需要的是file类型的,所以这个时候用createReadStream获取的file类型
2, 需要特别注意的是:图片上传的时候请求头里有一个boundary随机数
刚开始我是自己拼接的随机数,但是发现一直不对提示:图片上传成功了,但是实际数据库是没有图片的,后来发现自己拼接的随机数会被解析成格式错误,后端无法识别,
这个时候可以用:
const req= new FormData()
req.append("file",file)
const headers = req.getHeaders()
axios.post(url,req,{headers }).then(res=>{
)