- 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 beprogrammed
- If you have such a need and want to implement it, why not give it a try with
Code Recycle
Import a service
- Create code snippet configuration
{"prefix":["import"],"body":" ","regexp":{"pattern":"\\.([\\p{L}\\p{N}]+)","flag":"u"},"pattern":"**/*.ts","dynamicMode":true,"script":"./import-class.ts"}
- Implement call function
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 thets
file in the editor, and completing the completion, theHello
class will be automatically introduced and initialized
More?
- examples
- The tool currently supports the execution of
CLI
andVSCode Extension
. Script Supportyaml
/js
/ts
- You can viewdocument learn more
- If you want to see more instances, you canvisit the repository view and Run
- If you are already interested, you canstart quickly
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse