HbuilderX 插件开发-模板创建
实现思路
- 使用HbuilderX 打开某个文档时右键
- 点击的时候获取当前打开的文档内容
- 使用 API 替换为自己的模板
示例
- package.json
{
"id": "SL-HbuilderX-Tool",
"name": "SL-HbuilderX-Tool",
"description": "快速创建html,vue2模板",
"displayName": "SL-HbuilderX-Tool",
"version": "1.0.1",
"publisher": "SL",
"engines": {
"HBuilderX": "^3.8.0"
},
"categories": [
"Other"
],
"keywords": [
"html",
"vue2",
"template"
],
"main": "./extension",
"activationEvents": [
"onCommand:extension.html",
"onCommand:extension.vue2"
],
"contributes": {
"commands": [{
"command": "extension.html",
"title": "创建HTML模板"
},{
"command": "extension.vue2",
"title": "创建VUE2模板"
}],
"menus": {
"editor/context": [{
"id": "foo",
"title": "SL-HbuilderX-Tool",
"group": "goto"
},
{
"command": "extension.html",
"group": "foo@1",
"when": "editorTextFocus"
},
{
"command": "extension.vue2",
"group": "foo@1",
"when": "editorTextFocus"
},
{
"group": "goto"
}
]
}
},
"extensionDependencies": [
"plugin-manager"
],
"dependencies": {}
}
- extension.js
var hx = require("hbuilderx");
let htmlTemp = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div>Hello World!!!</div>
</body>
</html>`
let vue2Temp = `<template>
<div>Hello World!!!</div>
</template>
<script>
export default {
name: "Index",
props: {},
watch:{},
computed:{},
data() {
return {}
},
beforeCreate() {
},
created() {
},
beforeMount() {
},
mounted() {
},
beforeDestroy() {
},
destroyed() {
},
methods: {}
}
</script>
<style scoped>
</style>`
//该方法将在插件激活的时候调用
function activate(context) {
let htmldisposable = hx.commands.registerCommand('extension.html', () => {
let activeEditor = hx.window.getActiveTextEditor();
activeEditor.then(function(editor) {
let text = editor.document.getText({});
editor.edit(editBuilder => {
editBuilder.replace({start:0,end:text.length}, htmlTemp);
});
});
});
let vue2disposable = hx.commands.registerCommand('extension.vue2', () => {
let activeEditor = hx.window.getActiveTextEditor();
activeEditor.then(function(editor) {
let text = editor.document.getText({});
editor.edit(editBuilder => {
editBuilder.replace({start:0,end:text.length}, vue2Temp);
});
});
});
//订阅销毁钩子,插件禁用的时候,自动注销该command。
context.subscriptions.push(htmldisposable);
context.subscriptions.push(vue2disposable);
}
//该方法将在插件禁用的时候调用(目前是在插件卸载的时候触发)
function deactivate() {
}
module.exports = {
activate,
deactivate
}
源代码
SL-HbuilderX-Tool