编写一个vscode的插件

编写一个vscode的插件

需求

  • 前端h5页面开发中,开发新功能都要从浏览器复制链接发送到微信然后打开
  • 原生端在webview中,调试本地的h5也要输入url地址,非常繁琐
  • 期望vscode可以自动生成一个二维码,供手机端扫码

准备

npm install -g yo generator-code
  • 生成demo
yo code

在这里插入图片描述

  • 根据提示,输入项目名称,扩展的内容等
  • 生成好的项目是一个默认的helloword插件
  • vscode打开项目
  • F5,会自动打开一个调试的vscode

开发自己的插件h5-helper

  • package.json
//  启动命令为h5-helper
 "activationEvents": [
    "onCommand:h5-helper.h5-helper"
  ],
  "main": "./extension.js",
  "contributes": {
    "commands": [
      // 配置的启动命令
      {
        "command": "h5-helper.h5-helper",
        "title": "h5-helper"
      }
    ],
    "menus": {
      // 配置文件内右键快捷键
      "editor/context": [
        {
          "when": "editorFocus",
          "command": "h5-helper.h5-helper",
          "group": "navigation"
        }
      ]
    }
  },
  • extension.js
  • getIpAddress方法,获取电脑的ip地址

(这里只获取了wifi下的,如果是网线链接,请自己修改方法)

  • getParams 获取配置文件的参数
  • QRCode 根据文本生成一个二维码
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const os = require("os");
const fs = require('fs')
const QRCode = require('qrcode')
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function getIpAddress() {
	/**os.networkInterfaces() 返回一个对象,该对象包含已分配了网络地址的网络接口 */
	var interfaces = os.networkInterfaces();
	console.log(interfaces)
	const {
		WLAN
	} = interfaces
	const ipv4 = WLAN.find(item => item.family === 'IPv4')
	return ipv4.address
}

function getParams(form) {
	let url = '';
	if(!form){
		return url
	}
	const keys = Object.keys(form);
	for (let i = 0; i < keys.length; i++) {
		if (!form[keys[i]]) {
			continue;
		}
		if (url) {
			url += `&${keys[i]}=${form[keys[i]]}`;
		} else {
			url += `?${keys[i]}=${form[keys[i]]}`;
		}
	}
	return url;
}
/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
	console.log('Congratulations, your extension "h5-helper" is now active!');
	let disposable = vscode.commands.registerCommand('h5-helper.h5-helper', function (uri) {
		// 文件路径 
		const filePath = uri.path.substring(1);
		fs.stat(filePath, (err, stats) => {
			if (err) {
				vscode.window.showErrorMessage(`获取文件时遇到错误了${err}!!!`)
			}
			if (stats.isDirectory()) {
				vscode.window.showWarningMessage(`检测的是文件夹,不是文件,请重新选择!!!`);
			}
			const splitFilePath = filePath.split('/')
			const fileName = splitFilePath[splitFilePath.length - 1]
			//  判断是否是需要的文件
			if (fileName !== 'h5-helper.json') {
				vscode.window.showWarningMessage(`请选中h5-helper.json文件,请重新选择!!!`);
				return
			}
			//  读取文件的内容
			const fileData = JSON.parse(fs.readFileSync(filePath).toString())
			const {
				port,
				projectName,
				params,
				appLinkConfig
			} = fileData
			let isAddAppLink = appLinkConfig.includes(projectName) ? 'applink/':''
			// 拼接成url路径
			const qrCodepath = `http://${getIpAddress()}:${port}/${isAddAppLink}${projectName}/${projectName}.html${getParams(params)}`
			// 开启一个新的页面,在页面中生成二维码
			const panel = vscode.window.createWebviewPanel(
				'Test', // 标识webview的类型
				'webview1', // 展示给用户的面板的标题
				vscode.ViewColumn.One, // 显示webview面板以编辑器新列的方式.
				{} // webview其他的选项
			)

			function getWebviewContent(imgPath, url) {
				return `<!DOCTYPE html>
		  <html lang="en">
		  <head>
			  <meta charset="UTF-8">
			  <meta name="viewport" content="width=device-width, initial-scale=1.0">
			  <title>Cat Coding</title>
		  </head>
		  <body>
			  <img src="${imgPath}" width="300" />
			  <p>${url}</p>
		  </body>
		  
		  </html>`;
			}
			// 创建一个二维码
			QRCode.toDataURL(qrCodepath, function (err, url) {
				panel.webview.html = getWebviewContent(url, qrCodepath);
			})
		});
	});
	context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}

打包

  • 安装打包工具

vsce版本过高会导致不能打包

yarn add vsce@1.6.0 -g
  • 执行打包命令
vsce package

在这里插入图片描述

  • 出现上图则是打包成功

可能会出现缺少作者提示,package.json中添加 “publisher”: “xiaoshunshi” 即可

插件的安装和使用

  • vscode中点击左侧扩展按钮
    在这里插入图片描述
  • 项目中根目录配置h5-helper.json

文件名称必须是h5-helper.json,不然会报错

{
    "port":8090, //端口号
    "projectName":"coupon", // 项目名称
    "appLinkConfig":["coupon"],// 是否需要添加前缀applink
    "params":{ // 链接参数
        "name":"xiaoshunshi"
    }
}
  • 在该文件窗口点击鼠标右键
    在这里插入图片描述
  • 在vscode会出现一个新的窗口,说明插件开发成功

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值