macro for code generation/precompilation
npm install @zwa73/macroREADME.md (English)
regionMacro to write text into a specific region in a file.
regionMacro function writes the codeText into the corresponding region.
regionId: The region id //#region ${id}.
codeText: The text to be written.
opt: Optional parameters.
opt.filePath: The target file. The default is the same name file without ".macro".
opt.glob: Use glob matching instead of file path.
commentMacro function writes the codeText under the corresponding comment.
commentId: The comment id // ${id}.
codeText: The text to be written.
opt: Optional parameters.
opt.filePath: The target file. The default is the same name file without ".macro".
opt.glob: Use glob matching instead of file path.
fileMacro function writes the codeText into the corresponding file. If the file does not exist, it will be created.
codeText: The text to be written.
opt: Optional parameters.
opt.filePath: The target file. The default is the same name file without ".macro".
opt.glob: Use glob matching instead of file path.
src/test.macro.ts:
typescript
import {regionMacro,commentMacro,fileMacro} from '@zwa73/macro';
regionMacro('region1', 'type Region = 1;');
commentMacro('comment1', 'type Comment = 1;');
fileMacro('type FileMacro = 1;',{filePath:'src/testFileMacro.ts'});
`
In src/test.ts:
`typescript
console.log(1);
//#region region1
//#endregion
console.log(2);
// comment1
// comment2
// comment3
`
After execution, in src/test.ts:
`typescript
console.log(1);
//#region region1
type Region = 1;
//#endregion
console.log(2);
// comment1
type Comment = 1;
// comment3
`
And create src/testFileMacro.ts:
`typescript
type FileMacro = 1;
`
Or more:
`typescript
function exportComment(glob:string){
commentMacro(/export (\S*)/,({filePath,execArr})=>{
const basedir = path.dirname(filePath).replaceAll('\\','/');
const result = fileSearchGlob(basedir,execArr[1],{normalize:'posix'})
.map((file)=>path.posix.relative(basedir,file))
.map((file)=>path.parse(file).name)
.filter((file)=>file!=path.parse(filePath).name)
.map((file)=>export * from './${file}')
.join(';');
return result.length>0? ${result}; : result;
},{glob:true,filePath:glob});
}
exportComment('src/**/index.ts');
`
In any index.ts:
`typescript
// export *
`
After execution:
`typescript
// export *
import from './YouModule1';import from './YouModule2'; //...
`
$3
This package also provides a command-line interface for generating code based on macros.
- -i, --include Include glob, default is src/*/.macro.ts
- -g, --exclude Exclude glob
- -p, --project Path to tsconfig, default is tsconfig.json
`powershell
npx zmacro Expand-Macro --include "src/*/.macro.ts" --project "tsconfig.json"
`
This command will run all files matching src/*/.macro.ts and generate code as shown in the example above.
Installs
`powershell
npm i --save-dev @zwa73/macro
``