@tomjs/create-app 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/index.mjs +6 -6
  2. package/package.json +1 -1
  3. package/template-electron-react/.vscode/launch.json +2 -3
  4. package/template-electron-react/.vscode/tasks.json +9 -3
  5. package/template-electron-react/README.md +0 -4
  6. package/template-electron-react/electron/main/index.ts +1 -1
  7. package/template-electron-react/package.json +3 -3
  8. package/template-electron-vue/.vscode/launch.json +2 -3
  9. package/template-electron-vue/.vscode/tasks.json +9 -3
  10. package/template-electron-vue/README.md +0 -4
  11. package/template-electron-vue/electron/main/index.ts +1 -1
  12. package/template-electron-vue/package.json +4 -4
  13. package/template-node/package.json +1 -1
  14. package/template-react/README.md +0 -4
  15. package/template-vscode-react/.eslintrc.cjs +7 -0
  16. package/template-vscode-react/.vscode/launch.json +21 -0
  17. package/template-vscode-react/.vscode/tasks.json +36 -0
  18. package/template-vscode-react/README.md +87 -0
  19. package/template-vscode-react/_lintstagedrc.cjs +5 -0
  20. package/template-vscode-react/extension/index.ts +14 -0
  21. package/template-vscode-react/extension/panels/MainPanel.ts +172 -0
  22. package/template-vscode-react/index.html +14 -0
  23. package/template-vscode-react/package.json +71 -0
  24. package/template-vscode-react/src/App.css +7 -0
  25. package/template-vscode-react/src/App.tsx +51 -0
  26. package/template-vscode-react/src/main.tsx +9 -0
  27. package/template-vscode-react/src/utils/index.ts +1 -0
  28. package/template-vscode-react/src/utils/vscode.ts +84 -0
  29. package/template-vscode-react/src/vite-env.d.ts +1 -0
  30. package/template-vscode-react/tsconfig.json +10 -0
  31. package/template-vscode-react/tsconfig.node.json +7 -0
  32. package/template-vscode-react/vite.config.ts +21 -0
  33. package/template-vscode-vue/.eslintrc.cjs +7 -0
  34. package/template-vscode-vue/.vscode/launch.json +21 -0
  35. package/template-vscode-vue/.vscode/tasks.json +36 -0
  36. package/template-vscode-vue/README.md +87 -0
  37. package/template-vscode-vue/_lintstagedrc.cjs +6 -0
  38. package/template-vscode-vue/extension/index.ts +14 -0
  39. package/template-vscode-vue/extension/panels/MainPanel.ts +172 -0
  40. package/template-vscode-vue/index.html +14 -0
  41. package/template-vscode-vue/package.json +69 -0
  42. package/template-vscode-vue/src/App.vue +58 -0
  43. package/template-vscode-vue/src/main.ts +4 -0
  44. package/template-vscode-vue/src/utils/index.ts +1 -0
  45. package/template-vscode-vue/src/utils/vscode.ts +84 -0
  46. package/template-vscode-vue/src/vite-env.d.ts +1 -0
  47. package/template-vscode-vue/tsconfig.json +10 -0
  48. package/template-vscode-vue/tsconfig.node.json +7 -0
  49. package/template-vscode-vue/vite.config.ts +21 -0
  50. package/template-vue/README.md +0 -4
  51. package/template-electron-react/scripts/builder.ts +0 -38
  52. package/template-electron-react/scripts/constants.ts +0 -19
  53. package/template-electron-react/scripts/release.ts +0 -40
  54. package/template-electron-vue/scripts/builder.ts +0 -38
  55. package/template-electron-vue/scripts/constants.ts +0 -19
  56. package/template-electron-vue/scripts/release.ts +0 -40
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import a,{renameSync as Ce}from"fs";import Oe from"os";import o from"path";import{fileURLToPath as Ne}from"url";import{blue as K,cyan as Fe,green as Te,red as fe,reset as w,yellow as X}from"kolorist";import{camelCase as De}from"lodash-es";import Ge from"minimist";import Ue from"prompts";import E from"shelljs";import pe from"os";import me from"path";import{blue as Re,red as C,reset as O}from"kolorist";import Pe from"minimist";import Y from"prompts";import l from"fs";import W from"path";function A(e){return[["t","template"],["g","git"]].forEach(([n,c])=>{e[c]=e[c]??e[n]}),e}function re(e){let n=l.readdirSync(e);return n.length===0||n.length===1&&n[0]===".git"}function J(e){return e?.trim().replace(/\/+$/g,"")}function Ee(e,n){l.mkdirSync(n,{recursive:!0});for(let c of l.readdirSync(e)){let y=W.resolve(e,c),m=W.resolve(n,c);M(y,m)}}function M(e,n){l.statSync(e).isDirectory()?Ee(e,n):l.copyFileSync(e,n)}function ie(e){if(l.existsSync(e))for(let n of l.readdirSync(e))n!==".git"&&l.rmSync(W.resolve(e,n),{recursive:!0,force:!0})}function z(e){return/^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(e)}function oe(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/^[._]/,"").replace(/[^a-z\d\-~]+/g,"-")}function se(e){if(!e)return;let c=e.split(" ")[0].split("/");return{name:c[0],version:c[1]}}function v(e){if(l.existsSync(e))try{return JSON.parse(l.readFileSync(e,"utf8"))}catch(n){console.error(n)}}function x(e,n){l.writeFileSync(e,JSON.stringify(n,null,2)+`
3
- `)}function $(e){l.existsSync(e)&&l.rmSync(e,{recursive:!0,force:!0})}function ce(e){l.existsSync(e)||l.mkdirSync(e,{recursive:!0})}var Ae=A(Pe(process.argv.slice(2),{string:["_"]})),ae={repo:"https://github.com",owner:pe.userInfo().username};function L(e){let{repo:n,owner:c}=e;return`${n}${n.endsWith("/")?"":"/"}${c}`}async function le(e){let n=await Y([{type:"text",name:"repo",message:O("Git repository url:"),initial:e?.repo||ae.repo},{type:"text",name:"owner",message:O("Git repository owner:"),initial:e?.owner||ae.owner}],{onCancel:()=>{throw console.log(C("\u2716")+" Operation cancelled"),new Error}});return{id:e?.id||Date.now().toString(),repo:n.repo,owner:n.owner}}var ue=me.join(pe.homedir(),".tomjs","create-app"),ge=me.join(ue,"config.json");function N(){return ce(ue),Object.assign({gitRepos:[]},v(ge))}function $e(e){let n=N();n.createTime?n.updateTime=Date.now():n.createTime=Date.now(),x(ge,Object.assign(n,e))}function V(e){$e({gitRepos:e})}async function H(){let{gitRepos:e}=N();(e.length===0||Ae.git)&&(e.length===0&&console.log(`You need to set the ${Re("git remote repository")} for the first time.`),await n());async function n(){let c=e.map(f=>({title:L(f),value:f.id})).concat([{title:"Add",value:"add"},{title:C("Exit"),value:"exit"}]),y=await Y({type:"select",name:"repoId",message:e.length===0?"You choose to add or exit:":"You can choose the repository to be operated, or choose to add or exit:",choices:c},{onCancel:()=>{throw console.log(C("\u2716")+" Operation cancelled"),new Error}}),{repoId:m}=y;if(m==="exit")return;if(m==="add"){let f=await le();return e.push(f),V(e),n()}let S=e.findIndex(f=>f.id===m),R=await Y([{type:"select",name:"action",message:O("Select an action?"),choices:[{title:"Edit",value:"edit"},{title:"Remove",value:"remove"},{title:"Exit",value:"exit"}]},{type:f=>f==="remove"&&"toggle",name:"confirmRemove",message:O("Where confirm to remove?"),initial:!0,active:"Yes",inactive:"No"}],{onCancel:()=>{throw console.log(C("\u2716")+" Operation cancelled"),new Error}}),{action:P,confirmRemove:F}=R;if(P==="exit")return H();if(P==="remove")return F&&(e.splice(S,1),V(e)),n();let T=await le(e[S]);return e[S]=T,V(e),n()}}var q=A(Ge(process.argv.slice(2),{string:["_"]})),B=process.cwd(),ve=[{name:"vue",display:"Vue",color:Te,variants:[{name:"vue",display:"Web",color:K},{name:"electron-vue",display:"Electron",color:X}]},{name:"react",display:"React",color:Fe,variants:[{name:"react",display:"Web",color:K},{name:"electron-react",display:"Electron",color:X}]},{name:"node",display:"Node",color:K,options:[{id:"test",name:"Test"},{id:"publish",name:"Git Repository + NPM Publish"},{id:"ssh",name:"Git init by SSH"},{id:"vite",name:"Vite Plugin"},{id:"electron",name:"Electron"},{id:"examples",name:"Examples"}]}],de=ve.map(e=>e.variants&&e.variants.map(n=>n.name)||[e.name]).reduce((e,n)=>e.concat(n),[]),Q="my-app";function ye(e){let n=E.exec(`git config --get ${e}`,{silent:!0});if(n.code===0)return n.stdout.trim()}function he(e){return e.length>1?e.substring(e.indexOf("/")+1):e}async function _e(){let e=J(q._[0]),n=q.template||q.t,c=e||Q,y=()=>c==="."?o.basename(o.resolve()):c,m=he(c),{gitRepos:S}=N(),R=await Ue([{type:e?null:"text",name:"projectName",message:w("Project name:"),initial:Q,onState:t=>{c=J(t.value)||Q,m=he(c)}},{type:()=>!a.existsSync(m)||re(m)?null:"toggle",name:"overwrite",message:()=>(m==="."?"Current directory":`Target directory "${m}"`)+" is not empty. Remove existing files and continue?",initial:!1,active:"Yes",inactive:"No"},{type:(t,{overwrite:r})=>{if(r===!1)throw console.log(fe("\u2716")+" Operation cancelled"),new Error;return null},name:"overwriteChecker"},{type:()=>z(y())?null:"text",name:"packageName",message:w("Package name:"),initial:()=>oe(y()),validate:t=>z(t)||"Invalid package.json name"},{type:n&&de.includes(n)?null:"select",name:"framework",message:typeof n=="string"&&!de.includes(n)?w(`"${n}" isn't a valid template. Please choose from below: `):w("Select a framework:"),initial:0,choices:ve.map(t=>{let r=t.color;return{title:r(t.display||t.name),value:t}})},{type:t=>t&&t.variants?"select":null,name:"variant",message:w("Select a variant:"),choices:t=>t?.variants?.map(r=>{let i=r.color;return{title:i(r.display||r.name),value:r.name}})},{type:(t,r)=>{let{framework:i}=r;return i&&Array.isArray(i.options)&&i.options.length?"multiselect":null},name:"options",message:w("Select optional options:"),instructions:!1,choices:(t,r)=>{let{framework:i}=r;return i?.options?.map(p=>({title:p.name,value:p.id}))}},{type:(t,r)=>S.length&&Array.isArray(r.options)&&r.options.includes("publish")?"select":null,name:"gitUserUrl",message:w("Which git repository to publish to?"),choices:S.map(t=>{let r=L(t);return{title:r,value:r}})}],{onCancel:()=>{throw console.log(fe("\u2716")+" Operation cancelled"),new Error}}),{framework:P,overwrite:F,packageName:T,variant:f,gitUserUrl:xe}=R,u=R.options||[],s=o.join(B,m);F?ie(s):a.existsSync(s)||a.mkdirSync(s,{recursive:!0}),console.log(`
4
- Scaffolding project in ${s}...`);let Z=f||P?.name||n||"",D=t=>o.join(Ne(import.meta.url),"../..",`template-${t}`),we=D(Z),G=Z.includes("node");[we,D("config")].forEach(t=>{let r=a.readdirSync(t);for(let i of r){let p=i.startsWith("_")?i.replace("_","."):i;if(G&&!u.includes("examples")&&i.includes("stylelint"))continue;let g=o.join(s,p);M(o.join(t,i),g)}});let h=T||y(),j={name:"UserName",email:"name@github.com"};function ee(t){let r=h.startsWith("@")?h.split("/")[0].substring(1):De(j.name),i=xe||`https://github.com/${r}`;return t&&(i=i.replace(/http(s):\/\//g,"git@").replace(/\//,":")),`${i}/${h.substring(h.indexOf("/")+1)}.git`}je(),G&&(Se(),ke(),be());let te=se(process.env.npm_config_user_agent),U=te?te.name:"npm";E.which("git")&&(E.exec(`cd ${s} && git init`),u.includes("publish")&&E.exec(`cd ${s} && git remote add origin ${ee(u.includes("ssh"))}`));let _=o.relative(B,s);switch(console.log(`
2
+ import a,{renameSync as $e}from"fs";import Ge from"os";import r from"path";import{fileURLToPath as Ne}from"url";import{lightBlue as O,lightCyan as Oe,lightGreen as F,lightYellow as Fe,red as fe,reset as w,yellow as Te}from"kolorist";import{camelCase as De}from"lodash-es";import Ue from"minimist";import _e from"prompts";import E from"shelljs";import pe from"os";import me from"path";import{blue as Re,red as $,reset as G}from"kolorist";import Pe from"minimist";import H from"prompts";import l from"fs";import W from"path";function A(e){return[["t","template"],["g","git"]].forEach(([n,c])=>{e[c]=e[c]??e[n]}),e}function ie(e){return l.readdirSync(e).length===0}function M(e){return e?.trim().replace(/\/+$/g,"")}function Ee(e,n){l.mkdirSync(n,{recursive:!0});for(let c of l.readdirSync(e)){let y=W.resolve(e,c),m=W.resolve(n,c);z(y,m)}}function z(e,n){l.statSync(e).isDirectory()?Ee(e,n):l.copyFileSync(e,n)}function oe(e){if(l.existsSync(e))for(let n of l.readdirSync(e))l.rmSync(W.resolve(e,n),{recursive:!0,force:!0})}function Y(e){return/^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(e)}function re(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/^[._]/,"").replace(/[^a-z\d\-~]+/g,"-")}function se(e){if(!e)return;let c=e.split(" ")[0].split("/");return{name:c[0],version:c[1]}}function v(e){if(l.existsSync(e))try{return JSON.parse(l.readFileSync(e,"utf8"))}catch(n){console.error(n)}}function x(e,n){l.writeFileSync(e,JSON.stringify(n,null,2)+`
3
+ `)}function C(e){l.existsSync(e)&&l.rmSync(e,{recursive:!0,force:!0})}function ce(e){l.existsSync(e)||l.mkdirSync(e,{recursive:!0})}var Ae=A(Pe(process.argv.slice(2),{string:["_"]})),ae={repo:"https://github.com",owner:pe.userInfo().username};function B(e){let{repo:n,owner:c}=e;return`${n}${n.endsWith("/")?"":"/"}${c}`}async function le(e){let n=await H([{type:"text",name:"repo",message:G("Git repository url:"),initial:e?.repo||ae.repo},{type:"text",name:"owner",message:G("Git repository owner:"),initial:e?.owner||ae.owner}],{onCancel:()=>{throw console.log($("\u2716")+" Operation cancelled"),new Error}});return{id:e?.id||Date.now().toString(),repo:n.repo,owner:n.owner}}var ue=me.join(pe.homedir(),".tomjs","create-app"),ge=me.join(ue,"config.json");function N(){return ce(ue),Object.assign({gitRepos:[]},v(ge))}function Ce(e){let n=N();n.createTime?n.updateTime=Date.now():n.createTime=Date.now(),x(ge,Object.assign(n,e))}function L(e){Ce({gitRepos:e})}async function K(){let{gitRepos:e}=N();(e.length===0||Ae.git)&&(e.length===0&&console.log(`You need to set the ${Re("git remote repository")} for the first time.`),await n());async function n(){let c=e.map(f=>({title:B(f),value:f.id})).concat([{title:"Add",value:"add"},{title:$("Exit"),value:"exit"}]),y=await H({type:"select",name:"repoId",message:e.length===0?"You choose to add or exit:":"You can choose the repository to be operated, or choose to add or exit:",choices:c},{onCancel:()=>{throw console.log($("\u2716")+" Operation cancelled"),new Error}}),{repoId:m}=y;if(m==="exit")return;if(m==="add"){let f=await le();return e.push(f),L(e),n()}let S=e.findIndex(f=>f.id===m),R=await H([{type:"select",name:"action",message:G("Select an action?"),choices:[{title:"Edit",value:"edit"},{title:"Remove",value:"remove"},{title:"Exit",value:"exit"}]},{type:f=>f==="remove"&&"toggle",name:"confirmRemove",message:G("Where confirm to remove?"),initial:!0,active:"Yes",inactive:"No"}],{onCancel:()=>{throw console.log($("\u2716")+" Operation cancelled"),new Error}}),{action:P,confirmRemove:T}=R;if(P==="exit")return K();if(P==="remove")return T&&(e.splice(S,1),L(e)),n();let D=await le(e[S]);return e[S]=D,L(e),n()}}var q=A(Ue(process.argv.slice(2),{string:["_"]})),Q=process.cwd(),ve=[{name:"web",display:"Web App",color:F,variants:[{name:"vue",display:"Vue",color:F},{name:"react",display:"React",color:O}]},{name:"electron",display:"Electron App",color:O,variants:[{name:"electron-vue",display:"Vue",color:F},{name:"electron-react",display:"React",color:O}]},{name:"vscode",display:"VSCode Extension",color:Oe,options:[{id:"publish",name:"Git Repository + NPM Publish"},{id:"ssh",name:"Git init by SSH"}],variants:[{name:"vscode-vue",display:"Vue",color:F},{name:"vscode-react",display:"React",color:O}]},{name:"node",display:"Node",color:Fe,options:[{id:"test",name:"Test"},{id:"publish",name:"Git Repository + NPM Publish"},{id:"ssh",name:"Git init by SSH"},{id:"vite",name:"Vite Plugin"},{id:"electron",name:"Electron"},{id:"examples",name:"Examples"}]}],de=ve.map(e=>e.variants&&e.variants.map(n=>n.name)||[e.name]).reduce((e,n)=>e.concat(n),[]),X="my-app";function ye(e){let n=E.exec(`git config --get ${e}`,{silent:!0});if(n.code===0)return n.stdout.trim()}function he(e){return e.length>1?e.substring(e.indexOf("/")+1):e}async function Ie(){let e=M(q._[0]),n=q.template||q.t,c=e||X,y=()=>c==="."?r.basename(r.resolve()):c,m=he(c),{gitRepos:S}=N(),R=await _e([{type:e?null:"text",name:"projectName",message:w("Project name:"),initial:X,onState:t=>{c=M(t.value)||X,m=he(c)}},{type:()=>!a.existsSync(m)||ie(m)?null:"toggle",name:"overwrite",message:()=>(m==="."?"Current directory":`Target directory "${m}"`)+" is not empty. Remove existing files and continue?",initial:!1,active:"Yes",inactive:"No"},{type:(t,{overwrite:i})=>{if(i===!1)throw console.log(fe("\u2716")+" Operation cancelled"),new Error;return null},name:"overwriteChecker"},{type:()=>Y(y())?null:"text",name:"packageName",message:w("Package name:"),initial:()=>re(y()),validate:t=>Y(t)||"Invalid package.json name"},{type:n&&de.includes(n)?null:"select",name:"framework",message:typeof n=="string"&&!de.includes(n)?w(`"${n}" isn't a valid template. Please choose from below: `):w("Select a framework:"),initial:0,choices:ve.map(t=>{let i=t.color;return{title:i(t.display||t.name),value:t}})},{type:t=>t&&t.variants?"select":null,name:"variant",message:w("Select a variant:"),choices:t=>t?.variants?.map(i=>{let o=i.color;return{title:o(i.display||i.name),value:i.name}})},{type:(t,i)=>{let{framework:o}=i;return o&&Array.isArray(o.options)&&o.options.length?"multiselect":null},name:"options",message:w("Select optional options:"),instructions:!1,choices:(t,i)=>{let{framework:o}=i;return o?.options?.map(p=>({title:p.name,value:p.id}))}},{type:(t,i)=>S.length&&Array.isArray(i.options)&&i.options.includes("publish")?"select":null,name:"gitUserUrl",message:w("Which git repository to publish to?"),choices:S.map(t=>{let i=B(t);return{title:i,value:i}})}],{onCancel:()=>{throw console.log(fe("\u2716")+" Operation cancelled"),new Error}}),{framework:P,overwrite:T,packageName:D,variant:f,gitUserUrl:xe}=R,u=R.options||[],s=r.join(Q,m);T?oe(s):a.existsSync(s)||a.mkdirSync(s,{recursive:!0}),console.log(`
4
+ Scaffolding project in ${s}...`);let Z=f||P?.name||n||"",U=t=>r.join(Ne(import.meta.url),"../..",`template-${t}`),we=U(Z),_=Z.includes("node");[we,U("config")].forEach(t=>{let i=a.readdirSync(t);for(let o of i){let p=o.startsWith("_")?o.replace("_","."):o;if(_&&!u.includes("examples")&&o.includes("stylelint"))continue;let g=r.join(s,p);z(r.join(t,o),g)}});let h=D||y(),j={name:"UserName",email:"name@github.com"};function ee(t=!1){let i=h.startsWith("@")?h.split("/")[0].substring(1):De(j.name),o=xe||`https://github.com/${i}`;return t&&(o=o.replace(/http(s):\/\//g,"git@").replace(/\//,":")),`${o}/${h.substring(h.indexOf("/")+1)}.git`}je(),_&&(Se(),ke(),be());let te=se(process.env.npm_config_user_agent),I=te?te.name:"npm";E.which("git")&&(E.exec(`cd ${s} && git init`),u.includes("publish")&&E.exec(`cd ${s} && git remote add origin ${ee(u.includes("ssh"))}`));let J=r.relative(Q,s);switch(console.log(`
5
5
  Done. Now run:
6
- `),s!==B&&console.log(` cd ${_.includes(" ")?`"${_}"`:_}`),U){case"yarn":console.log(" yarn"),console.log(" yarn dev");break;default:console.log(` ${U} install`),console.log(` ${U} run dev`);break}function Se(){["LICENSE","README.md","README.zh_CN.md"].forEach(t=>{let r=o.join(s,t);if(!u.includes("publish")&&a.existsSync(r)){a.rmSync(r),t==="README.md"&&a.writeFileSync(r,`# ${h}
7
- `,{encoding:"utf-8"});return}if(!a.existsSync(r))return;let i=a.readFileSync(r,"utf-8").replace(new RegExp("{{pkg.name}}","g"),h).replace(new RegExp("{{user.name}}","g"),j.name).replace(new RegExp("{{user.email}}","g"),j.email);a.writeFileSync(r,i)})}function k(t,...r){["dependencies","devDependencies"].forEach(i=>{Object.keys(t[i]||{}).forEach(p=>{r.find(g=>p.includes(g))&&delete t[i][p]})})}function je(){let t=v(o.join(s,"package.json"));t.name=h,u.includes("publish")?(E.which("git")&&(j.name=ye("user.name")||Oe.userInfo().username,j.email=ye("user.email")||"",t.author=Object.assign(t.author,j)),t.repository.url=`git+${ee()}`):(delete t.author,delete t.publishConfig,delete t.repository,delete t.scripts.prepublishOnly,delete t.devDependencies.np),G&&(u.includes("electron")||(k(t,"electron"),t.scripts["lint:eslint"]=t.scripts["lint:eslint"].replace(",electron","")),u.includes("vite")||k(t,"vite")),x(o.join(s,"package.json"),t)}function I(t,r){let i=t.lastIndexOf("."),p=t.substring(0,i)+"."+r+t.substring(i),g=o.join(s,t),d=o.join(s,p);u.includes(r)?($(g),a.existsSync(d)&&Ce(d,g)):$(d)}function ke(){if(I("tsconfig.json","test"),I("jest.config.cjs","electron"),u.includes("test"))return;a.readdirSync(s).filter(i=>i.startsWith("jest.config")||["test"].includes(i)).forEach(i=>{$(o.join(s,i))});let t=o.join(s,"package.json"),r=v(t);delete r.scripts.test,r.scripts["lint:eslint"]=r.scripts["lint:eslint"].replace(",test",""),k(r,"jest"),x(t,r)}function be(){if(I(".lintstagedrc.cjs","examples"),!u.includes("examples")){let i=v(o.join(s,"package.json"));i.scripts.lint=i.scripts.lint.replace(" lint:stylelint",""),i.scripts["lint:eslint"]=i.scripts["lint:eslint"].replace(",examples",""),delete i.scripts["lint:stylelint"],k(i,"stylelint"),x(o.join(s,"package.json"),i);return}let t=o.join(s,"examples");a.mkdirSync(t);let r=u.includes("electron");["vue","react"].forEach(i=>{let p=D(r?`electron-${i}`:i),g=o.join(t,i);if(!a.existsSync(p)){console.log(`${X(p)} template is not exist`);return}a.cpSync(p,g,{recursive:!0});let d=v(o.join(g,"package.json"));Object.keys(d.scripts).forEach(b=>{(b.startsWith("lint")||["prepare"].includes(b))&&delete d.scripts[b]}),k(d,"eslint","prettier","stylelint","commitlint","husky","lint-staged","tsconfig","lint-staged","npm-run-all"),x(o.join(g,"package.json"),d),["_lintstagedrc.cjs"].forEach(b=>{let ne=o.join(g,b);a.existsSync(ne)&&a.rmSync(ne,{recursive:!0})})}),a.writeFileSync(o.join(s,"pnpm-workspace.yaml"),`packages:
8
- - 'examples/*'`,{encoding:"utf-8"})}}H().then(async()=>_e().catch(e=>{e.message&&console.error(e)})).catch(e=>{e.message&&console.error(e)});
6
+ `),s!==Q&&console.log(` cd ${J.includes(" ")?`"${J}"`:J}`),I){case"yarn":console.log(" yarn"),console.log(" yarn dev");break;default:console.log(` ${I} install`),console.log(` ${I} run dev`);break}function Se(){["LICENSE","README.md","README.zh_CN.md"].forEach(t=>{let i=r.join(s,t);if(!u.includes("publish")&&a.existsSync(i)){a.rmSync(i),t==="README.md"&&a.writeFileSync(i,`# ${h}
7
+ `,{encoding:"utf-8"});return}if(!a.existsSync(i))return;let o=a.readFileSync(i,"utf-8").replace(new RegExp("{{pkg.name}}","g"),h).replace(new RegExp("{{user.name}}","g"),j.name).replace(new RegExp("{{user.email}}","g"),j.email);a.writeFileSync(i,o)})}function k(t,...i){["dependencies","devDependencies"].forEach(o=>{Object.keys(t[o]||{}).forEach(p=>{i.find(g=>p.includes(g))&&delete t[o][p]})})}function je(){let t=v(r.join(s,"package.json"));t.name=h,u.includes("publish")?(E.which("git")&&(j.name=ye("user.name")||Ge.userInfo().username,j.email=ye("user.email")||"",t.author=Object.assign(t.author,j)),t.publishConfig={access:"public",registry:"https://registry.npmjs.org/"},t.repository??={type:"git"},t.repository.url=`git+${ee()}`):(delete t.author,delete t.publishConfig,delete t.repository,delete t.scripts.prepublishOnly,delete t.devDependencies.np),_&&(u.includes("electron")||(k(t,"electron"),t.scripts["lint:eslint"]=t.scripts["lint:eslint"].replace(",electron","")),u.includes("vite")||k(t,"vite")),x(r.join(s,"package.json"),t)}function V(t,i){let o=t.lastIndexOf("."),p=t.substring(0,o)+"."+i+t.substring(o),g=r.join(s,t),d=r.join(s,p);u.includes(i)?(C(g),a.existsSync(d)&&$e(d,g)):C(d)}function ke(){if(V("tsconfig.json","test"),V("jest.config.cjs","electron"),u.includes("test"))return;a.readdirSync(s).filter(o=>o.startsWith("jest.config")||["test"].includes(o)).forEach(o=>{C(r.join(s,o))});let t=r.join(s,"package.json"),i=v(t);delete i.scripts.test,i.scripts["lint:eslint"]=i.scripts["lint:eslint"].replace(",test",""),k(i,"jest"),x(t,i)}function be(){if(V(".lintstagedrc.cjs","examples"),!u.includes("examples")){let o=v(r.join(s,"package.json"));o.scripts.lint=o.scripts.lint.replace(" lint:stylelint",""),o.scripts["lint:eslint"]=o.scripts["lint:eslint"].replace(",examples",""),delete o.scripts["lint:stylelint"],k(o,"stylelint"),x(r.join(s,"package.json"),o);return}let t=r.join(s,"examples");a.mkdirSync(t);let i=u.includes("electron");["vue","react"].forEach(o=>{let p=U(i?`electron-${o}`:o),g=r.join(t,o);if(!a.existsSync(p)){console.log(`${Te(p)} template is not exist`);return}a.cpSync(p,g,{recursive:!0});let d=v(r.join(g,"package.json"));Object.keys(d.scripts).forEach(b=>{(b.startsWith("lint")||["prepare"].includes(b))&&delete d.scripts[b]}),k(d,"eslint","prettier","stylelint","commitlint","husky","lint-staged","tsconfig","lint-staged","npm-run-all"),x(r.join(g,"package.json"),d),["_lintstagedrc.cjs"].forEach(b=>{let ne=r.join(g,b);a.existsSync(ne)&&a.rmSync(ne,{recursive:!0})})}),a.writeFileSync(r.join(s,"pnpm-workspace.yaml"),`packages:
8
+ - 'examples/*'`,{encoding:"utf-8"})}}K().then(async()=>Ie().catch(e=>{e.message&&console.error(e)})).catch(e=>{e.message&&console.error(e)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomjs/create-app",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "create tomjs web app",
5
5
  "keywords": [
6
6
  "tomjs",
@@ -6,7 +6,6 @@
6
6
  "configurations": [
7
7
  {
8
8
  "name": "Debug Main Process",
9
- "preLaunchTask": "npm:debug",
10
9
  "type": "node",
11
10
  "request": "launch",
12
11
  "cwd": "${workspaceFolder}",
@@ -23,7 +22,7 @@
23
22
  "${workspaceFolder}/**/*.mjs",
24
23
  "!**/node_modules/**"
25
24
  ],
26
- "envFile": "${workspaceFolder}/node_modules/@tomjs/vite-plugin-electron/debug/.env"
27
- },
25
+ "preLaunchTask": "${defaultBuildTask}",
26
+ }
28
27
  ]
29
28
  }
@@ -4,11 +4,9 @@
4
4
  "version": "2.0.0",
5
5
  "tasks": [
6
6
  {
7
- "label": "npm:debug",
8
7
  "type": "npm",
9
- "script": "debug",
8
+ "script": "dev",
10
9
  "detail": "cross-env VITE_ELECTRON_DEBUG=1 vite",
11
- "isBackground": true,
12
10
  "problemMatcher": {
13
11
  "owner": "typescript",
14
12
  "fileLocation": "relative",
@@ -25,6 +23,14 @@
25
23
  "beginsPattern": "^.*VITE v.* ready in \\d* ms.*$",
26
24
  "endsPattern": "^.*\\[@tomjs:electron\\] startup electron*$"
27
25
  }
26
+ },
27
+ "isBackground": true,
28
+ "presentation": {
29
+ "reveal": "never"
30
+ },
31
+ "group": {
32
+ "kind": "build",
33
+ "isDefault": true
28
34
  }
29
35
  }
30
36
  ]
@@ -95,7 +95,3 @@ Run `Debug Main Process` through `vscode` to debug the main thread. For debuggin
95
95
  ]
96
96
  }
97
97
  ```
98
-
99
- ## Reference project
100
-
101
- - [electron-vite-react](https://github.com/electron-vite/electron-vite-react)
@@ -24,7 +24,7 @@ const isDev = process.env.NODE_ENV === 'development';
24
24
  let win: BrowserWindow | null = null;
25
25
  // package.json "type":"module", must use mjs extension
26
26
  const preload = join(__dirname, '../preload/index.mjs');
27
- const serverUrl = process.env.APP_DEV_SERVER_URL as string;
27
+ const serverUrl = process.env.VITE_DEV_SERVER_URL as string;
28
28
  const rendererDist = join(__dirname, '../renderer');
29
29
  const indexHtml = join(rendererDist, 'index.html');
30
30
  const publicPath = serverUrl ? join(__dirname, '../../public') : rendererDist;
@@ -11,7 +11,7 @@
11
11
  "dev": "vite",
12
12
  "debug": "cross-env VITE_ELECTRON_DEBUG=1 npm run dev",
13
13
  "build": "npm run clean && vite build",
14
- "build:pack": "cross-env VITE_ELECTRON_BUILDER=1 npm run build",
14
+ "release": "cross-env VITE_ELECTRON_BUILDER=1 npm run build",
15
15
  "clean": "rimraf ./dist",
16
16
  "lint": "run-s lint:eslint lint:stylelint lint:prettier",
17
17
  "lint:eslint": "eslint \"{src,electron,scripts}/**/*.{ts,tsx}\" *.{js,cjs,ts} --fix --cache",
@@ -31,7 +31,7 @@
31
31
  "@tomjs/prettier": "^1.0.9",
32
32
  "@tomjs/stylelint": "^2.0.2",
33
33
  "@tomjs/tsconfig": "^1.1.5",
34
- "@tomjs/vite-plugin-electron": "^1.6.0",
34
+ "@tomjs/vite-plugin-electron": "^1.7.0",
35
35
  "@types/node": "^18.19.3",
36
36
  "@types/react": "^18.2.45",
37
37
  "@types/react-dom": "^18.2.18",
@@ -46,7 +46,7 @@
46
46
  "prettier": "^3.1.1",
47
47
  "rimraf": "^5.0.5",
48
48
  "stylelint": "^16.0.2",
49
- "tsx": "^4.6.2",
49
+ "tsx": "^4.7.0",
50
50
  "typescript": "~5.3.3",
51
51
  "vite": "^5.0.10",
52
52
  "vite-plugin-electron-renderer": "^0.14.5"
@@ -6,7 +6,6 @@
6
6
  "configurations": [
7
7
  {
8
8
  "name": "Debug Main Process",
9
- "preLaunchTask": "npm:debug",
10
9
  "type": "node",
11
10
  "request": "launch",
12
11
  "cwd": "${workspaceFolder}",
@@ -23,7 +22,7 @@
23
22
  "${workspaceFolder}/**/*.mjs",
24
23
  "!**/node_modules/**"
25
24
  ],
26
- "envFile": "${workspaceFolder}/node_modules/@tomjs/vite-plugin-electron/debug/.env"
27
- },
25
+ "preLaunchTask": "${defaultBuildTask}"
26
+ }
28
27
  ]
29
28
  }
@@ -4,11 +4,9 @@
4
4
  "version": "2.0.0",
5
5
  "tasks": [
6
6
  {
7
- "label": "npm:debug",
8
7
  "type": "npm",
9
- "script": "debug",
8
+ "script": "dev",
10
9
  "detail": "cross-env VITE_ELECTRON_DEBUG=1 vite",
11
- "isBackground": true,
12
10
  "problemMatcher": {
13
11
  "owner": "typescript",
14
12
  "fileLocation": "relative",
@@ -25,6 +23,14 @@
25
23
  "beginsPattern": "^.*VITE v.* ready in \\d* ms.*$",
26
24
  "endsPattern": "^.*\\[@tomjs:electron\\] startup electron*$"
27
25
  }
26
+ },
27
+ "isBackground": true,
28
+ "presentation": {
29
+ "reveal": "never"
30
+ },
31
+ "group": {
32
+ "kind": "build",
33
+ "isDefault": true
28
34
  }
29
35
  }
30
36
  ]
@@ -90,7 +90,3 @@ Run `Debug Main Process` through `vscode` to debug the main thread. For debuggin
90
90
  ]
91
91
  }
92
92
  ```
93
-
94
- ## Reference project
95
-
96
- - [electron-vite-vue](https://github.com/electron-vite/electron-vite-vue)
@@ -24,7 +24,7 @@ const isDev = process.env.NODE_ENV === 'development';
24
24
  let win: BrowserWindow | null = null;
25
25
  // package.json "type":"module", must use mjs extension
26
26
  const preload = join(__dirname, '../preload/index.mjs');
27
- const serverUrl = process.env.APP_DEV_SERVER_URL as string;
27
+ const serverUrl = process.env.VITE_DEV_SERVER_URL as string;
28
28
  const rendererDist = join(__dirname, '../renderer');
29
29
  const indexHtml = join(rendererDist, 'index.html');
30
30
  const publicPath = serverUrl ? join(__dirname, '../../public') : rendererDist;
@@ -11,10 +11,10 @@
11
11
  "dev": "vite",
12
12
  "debug": "cross-env VITE_ELECTRON_DEBUG=1 npm run dev",
13
13
  "build": "npm run clean && vue-tsc --noEmit && vite build",
14
- "build:pack": "cross-env VITE_ELECTRON_BUILDER=1 npm run build",
14
+ "release": "cross-env VITE_ELECTRON_BUILDER=1 npm run build",
15
15
  "clean": "rimraf ./dist",
16
16
  "lint": "run-s lint:eslint lint:stylelint lint:prettier",
17
- "lint:eslint": "eslint \"{src,electron,scripts}/**/*.{js,cjs,ts,vue}\" *.{js,cjs,ts} --fix --cache",
17
+ "lint:eslint": "eslint \"{src,electron,scripts}/**/*.{js,cjs,ts,tsx,vue}\" *.{js,cjs,ts} --fix --cache",
18
18
  "lint:stylelint": "stylelint \"{src,electron,scripts}/**/*.{css,scss,less,html}\" --fix --cache",
19
19
  "lint:prettier": "prettier --write .",
20
20
  "prepare": "husky install"
@@ -30,7 +30,7 @@
30
30
  "@tomjs/prettier": "^1.0.9",
31
31
  "@tomjs/stylelint": "^2.0.2",
32
32
  "@tomjs/tsconfig": "^1.1.5",
33
- "@tomjs/vite-plugin-electron": "^1.6.0",
33
+ "@tomjs/vite-plugin-electron": "^1.7.0",
34
34
  "@types/node": "^18.19.3",
35
35
  "@vitejs/plugin-vue": "^4.5.2",
36
36
  "cross-env": "^7.0.3",
@@ -43,7 +43,7 @@
43
43
  "prettier": "^3.1.1",
44
44
  "rimraf": "^5.0.5",
45
45
  "stylelint": "^16.0.2",
46
- "tsx": "^4.6.2",
46
+ "tsx": "^4.7.0",
47
47
  "typescript": "~5.3.3",
48
48
  "vite": "^5.0.10",
49
49
  "vite-plugin-electron-renderer": "^0.14.5",
@@ -73,7 +73,7 @@
73
73
  "stylelint": "^16.0.2",
74
74
  "ts-jest": "^29.1.1",
75
75
  "tsup": "^8.0.1",
76
- "tsx": "^4.6.2",
76
+ "tsx": "^4.7.0",
77
77
  "typescript": "~5.3.3",
78
78
  "vite": "^5.0.10"
79
79
  }
@@ -1,7 +1,3 @@
1
1
  # react
2
2
 
3
3
  vite + react
4
-
5
- ## Reference project
6
-
7
- - [create-vite](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts)
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ env: {
3
+ node: true,
4
+ es6: true,
5
+ },
6
+ extends: [require.resolve('@tomjs/eslint/react/typescript')],
7
+ };
@@ -0,0 +1,21 @@
1
+ // A launch configuration that compiles the extension and then opens it inside a new window
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ {
6
+ "version": "0.2.0",
7
+ "configurations": [
8
+ {
9
+ "name": "Run Extension",
10
+ "type": "extensionHost",
11
+ "request": "launch",
12
+ "args": [
13
+ "--extensionDevelopmentPath=${workspaceFolder}"
14
+ ],
15
+ "outFiles": [
16
+ "${workspaceFolder}/dist/extension/*.js"
17
+ ],
18
+ "preLaunchTask": "${defaultBuildTask}"
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,36 @@
1
+ // See https://go.microsoft.com/fwlink/?LinkId=733558
2
+ // for the documentation about the tasks.json format
3
+ {
4
+ "version": "2.0.0",
5
+ "tasks": [
6
+ {
7
+ "type": "npm",
8
+ "script": "dev",
9
+ "problemMatcher": {
10
+ "owner": "typescript",
11
+ "fileLocation": "relative",
12
+ "pattern": {
13
+ "regexp": "^([a-zA-Z]\\:\/?([\\w\\-]\/?)+\\.\\w+):(\\d+):(\\d+): (ERROR|WARNING)\\: (.*)$",
14
+ "file": 1,
15
+ "line": 3,
16
+ "column": 4,
17
+ "code": 5,
18
+ "message": 6
19
+ },
20
+ "background": {
21
+ "activeOnStart": true,
22
+ "beginsPattern": "^.*extension build start*$",
23
+ "endsPattern": "^.*extension (build|rebuild) success.*$"
24
+ }
25
+ },
26
+ "isBackground": true,
27
+ "presentation": {
28
+ "reveal": "never"
29
+ },
30
+ "group": {
31
+ "kind": "build",
32
+ "isDefault": true
33
+ }
34
+ }
35
+ ]
36
+ }
@@ -0,0 +1,87 @@
1
+ # extension-vue
2
+
3
+ vite + extension + vue
4
+
5
+ ## Description
6
+
7
+ - Recommend `extension` and page `src` code directory structure
8
+
9
+ ```
10
+ |--extension // extension code
11
+ | |--index.ts
12
+ |--src // front-end code
13
+ | |--App.vue
14
+ | |--main.ts
15
+ ```
16
+
17
+ - Zero configuration, default dist output directory
18
+
19
+ ```
20
+ |--dist
21
+ | |--extension
22
+ | | |--index.js
23
+ | | |--index.js.map
24
+ | |--webview
25
+ | | |--index.html
26
+ ```
27
+
28
+ ## Debug
29
+
30
+ Run `Run Extension` through `vscode` to debug. For debugging tools, refer to [Official Documentation](https://code.visualstudio.com/docs/editor/debugging)
31
+
32
+ `launch.json` is configured as follows:
33
+
34
+ ```json
35
+ {
36
+ "version": "0.2.0",
37
+ "configurations": [
38
+ {
39
+ "name": "Run Extension",
40
+ "type": "extensionHost",
41
+ "request": "launch",
42
+ "args": ["--extensionDevelopmentPath=${workspaceFolder}"],
43
+ "outFiles": ["${workspaceFolder}/dist/extension/*.js"],
44
+ "preLaunchTask": "${defaultBuildTask}"
45
+ }
46
+ ]
47
+ }
48
+ ```
49
+
50
+ `tasks.json` is configured as follows:
51
+
52
+ ```json
53
+ {
54
+ "version": "2.0.0",
55
+ "tasks": [
56
+ {
57
+ "type": "npm",
58
+ "script": "dev",
59
+ "problemMatcher": {
60
+ "owner": "typescript",
61
+ "fileLocation": "relative",
62
+ "pattern": {
63
+ "regexp": "^([a-zA-Z]\\:/?([\\w\\-]/?)+\\.\\w+):(\\d+):(\\d+): (ERROR|WARNING)\\: (.*)$",
64
+ "file": 1,
65
+ "line": 3,
66
+ "column": 4,
67
+ "code": 5,
68
+ "message": 6
69
+ },
70
+ "background": {
71
+ "activeOnStart": true,
72
+ "beginsPattern": "^.*extension build start*$",
73
+ "endsPattern": "^.*extension (build|rebuild) success.*$"
74
+ }
75
+ },
76
+ "isBackground": true,
77
+ "presentation": {
78
+ "reveal": "never"
79
+ },
80
+ "group": {
81
+ "kind": "build",
82
+ "isDefault": true
83
+ }
84
+ }
85
+ ]
86
+ }
87
+ ```
@@ -0,0 +1,5 @@
1
+ module.exports = {
2
+ '*.{js,cjs,ts,tsx}': ['eslint --fix', 'prettier --write'],
3
+ '*.{json,md}': ['prettier --write'],
4
+ '*.{css,scss,less,html}': ['stylelint --fix', 'prettier --write'],
5
+ };
@@ -0,0 +1,14 @@
1
+ import { commands, ExtensionContext } from 'vscode';
2
+ import { MainPanel } from './panels/MainPanel';
3
+
4
+ export function activate(context: ExtensionContext) {
5
+ // Create the show hello world command
6
+ const showHelloWorldCommand = commands.registerCommand('hello-world.showHelloWorld', async () => {
7
+ MainPanel.render(context.extensionUri);
8
+ });
9
+
10
+ // Add command to the extension context
11
+ context.subscriptions.push(showHelloWorldCommand);
12
+ }
13
+
14
+ export function deactivate() {}
@@ -0,0 +1,172 @@
1
+ import { Disposable, Uri, ViewColumn, Webview, WebviewPanel, window } from 'vscode';
2
+ // import __getWebviewHtml from '@tomjs/vscode-extension-webview';
3
+
4
+ function uuid() {
5
+ let text = '';
6
+ const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7
+ for (let i = 0; i < 32; i++) {
8
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
9
+ }
10
+ return text;
11
+ }
12
+
13
+ function getUri(webview: Webview, extensionUri: Uri, pathList: string[]) {
14
+ return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList));
15
+ }
16
+
17
+ /**
18
+ * This class manages the state and behavior of HelloWorld webview panels.
19
+ *
20
+ * It contains all the data and methods for:
21
+ *
22
+ * - Creating and rendering HelloWorld webview panels
23
+ * - Properly cleaning up and disposing of webview resources when the panel is closed
24
+ * - Setting the HTML (and by proxy CSS/JavaScript) content of the webview panel
25
+ * - Setting message listeners so data can be passed between the webview and extension
26
+ */
27
+ export class MainPanel {
28
+ public static currentPanel: MainPanel | undefined;
29
+ private readonly _panel: WebviewPanel;
30
+ private _disposables: Disposable[] = [];
31
+
32
+ /**
33
+ * The HelloWorldPanel class private constructor (called only from the render method).
34
+ *
35
+ * @param panel A reference to the webview panel
36
+ * @param extensionUri The URI of the directory containing the extension
37
+ */
38
+ private constructor(panel: WebviewPanel, extensionUri: Uri) {
39
+ this._panel = panel;
40
+
41
+ // Set an event listener to listen for when the panel is disposed (i.e. when the user closes
42
+ // the panel or when the panel is closed programmatically)
43
+ this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
44
+
45
+ // Set the HTML content for the webview panel
46
+ this._panel.webview.html = this._getWebviewContent(this._panel.webview, extensionUri);
47
+
48
+ // Set an event listener to listen for messages passed from the webview context
49
+ this._setWebviewMessageListener(this._panel.webview);
50
+ }
51
+
52
+ /**
53
+ * Renders the current webview panel if it exists otherwise a new webview panel
54
+ * will be created and displayed.
55
+ *
56
+ * @param extensionUri The URI of the directory containing the extension.
57
+ */
58
+ public static render(extensionUri: Uri) {
59
+ if (MainPanel.currentPanel) {
60
+ // If the webview panel already exists reveal it
61
+ MainPanel.currentPanel._panel.reveal(ViewColumn.One);
62
+ } else {
63
+ // If a webview panel does not already exist create and show a new one
64
+ const panel = window.createWebviewPanel(
65
+ // Panel view type
66
+ 'showHelloWorld',
67
+ // Panel title
68
+ 'Hello World',
69
+ // The editor column the panel should be displayed in
70
+ ViewColumn.One,
71
+ // Extra panel configurations
72
+ {
73
+ // Enable JavaScript in the webview
74
+ enableScripts: true,
75
+ // Restrict the webview to only load resources from the `dist/webview` directories
76
+ localResourceRoots: [Uri.joinPath(extensionUri, 'dist/webview')],
77
+ },
78
+ );
79
+
80
+ MainPanel.currentPanel = new MainPanel(panel, extensionUri);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Cleans up and disposes of webview resources when the webview panel is closed.
86
+ */
87
+ public dispose() {
88
+ MainPanel.currentPanel = undefined;
89
+
90
+ // Dispose of the current webview panel
91
+ this._panel.dispose();
92
+
93
+ // Dispose of all disposables (i.e. commands) for the current webview panel
94
+ while (this._disposables.length) {
95
+ const disposable = this._disposables.pop();
96
+ if (disposable) {
97
+ disposable.dispose();
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Defines and returns the HTML that should be rendered within the webview panel.
104
+ *
105
+ * @remarks This is also the place where references to the Vue webview build files
106
+ * are created and inserted into the webview HTML.
107
+ *
108
+ * @param webview A reference to the extension webview
109
+ * @param extensionUri The URI of the directory containing the extension
110
+ * @returns A template string literal containing the HTML that should be
111
+ * rendered within the webview panel
112
+ */
113
+ private _getWebviewContent(webview: Webview, extensionUri: Uri) {
114
+ // The CSS file from the Vue build output
115
+ const stylesUri = getUri(webview, extensionUri, ['dist', 'webview', 'assets', 'index.css']);
116
+ // The JS file from the Vue build output
117
+ const scriptUri = getUri(webview, extensionUri, ['dist', 'webview', 'assets', 'index.js']);
118
+
119
+ const nonce = uuid();
120
+
121
+ if (process.env.VITE_DEV_SERVER_URL) {
122
+ // @ts-ignore
123
+ return __getWebviewHtml({ serverUrl: process.env.VITE_DEV_SERVER_URL });
124
+ }
125
+
126
+ // Tip: Install the es6-string-html VS Code extension to enable code highlighting below
127
+ return /*html*/ `
128
+ <!doctype html>
129
+ <html lang="en">
130
+ <head>
131
+ <meta charset="UTF-8" />
132
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
133
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
134
+ <script type="module" crossorigin nonce="${nonce}" src="${scriptUri}"></script>
135
+ <link rel="stylesheet" crossorigin href="${stylesUri}">
136
+ <title>Hello World</title>
137
+ </head>
138
+ <body>
139
+ <div id="app"></div>
140
+ </body>
141
+ </html>
142
+ `;
143
+ }
144
+
145
+ /**
146
+ * Sets up an event listener to listen for messages passed from the webview context and
147
+ * executes code based on the message that is recieved.
148
+ *
149
+ * @param webview A reference to the extension webview
150
+ * @param context A reference to the extension context
151
+ */
152
+ private _setWebviewMessageListener(webview: Webview) {
153
+ webview.onDidReceiveMessage(
154
+ (message: any) => {
155
+ const command = message.command;
156
+ const text = message.text;
157
+ console.log(`command: ${command}`);
158
+
159
+ switch (command) {
160
+ case 'hello':
161
+ // Code that should run in response to the hello message command
162
+ window.showInformationMessage(text);
163
+ return;
164
+ // Add more switch case statements here as more webview message commands
165
+ // are created within the webview context (i.e. inside media/main.js)
166
+ }
167
+ },
168
+ undefined,
169
+ this._disposables,
170
+ );
171
+ }
172
+ }