How to customize code snippets in the editor? Provide the completion prefix, provide the completion content, and then you can use it directly
But specific content can only be inserted in the current file and input location, sometimes it may not meet the requirements
If we want to introduce a service that automatically creates when it does not exist, we can only rely on ourselves because the code snippet is static and cannot be programmed
If you have such a need and want to implement it, why not give it a try with Code Recycle
letfn:ScriptFunction=async (util,rule,host,injector)=>{letimportName=util.documentContext.snippetParameters![1];let_=util.lodash;letclassName=_.upperFirst(_.camelCase(importName));letrootCtx=util.initContext();awaitutil.changeList([// Check if the class exists{path:`*.ts`,name:'classPath',glob:true,list:[{query:`export class ${className}`,mode:'like',optional:true,callback(context,index){letclassPathCtx=context.getContext('root.classPath');classPathCtx.data=context.node!.path!;},},],},],rootCtx);letfilePath=rootCtx.getContext('root.classPath').data;if (!filePath){// Create from templateawaitutil.changeList([{type:'copy',from:join(__dirname,'./template/__name@dasherize__.ts'),to:'./',pathTemplate:'@angular-devkit',contentTemplate:'@angular-devkit',templateContext:{name:importName},},]);letchangedRecord=host.records();filePath=util.path.normalize((changedRecord[0]asany).path);}letpathRelative=require('../shared/path-relative');// insert referenceletchanged=awaitutil.changeList([{path:util.filePathGroup.currentPath,list:[{range:[0,0],replace:`import {${className}} from '${pathRelative(util.filePathGroup.currentPath,filePath,util)}'\n`,},{range:util.documentContext.insertRange![0].range,replace:`let ${importName} = new ${className}()`,},],},]);awaitutil.updateChangeList(changed);};
When entering import.hello in the ts file in the editor, and completing the completion, the Hello class will be automatically introduced and initialized
Top comments (0)