using.macro
Just plain old C++ RAII (or C# using
declaration) implementation for TypeScipt via 'babel-plugin-macros'
.
⚡️ Rationale
Suppose you have a local resource handle that you must manually release in the same scope.
With this plugin the cleanup is done automatically for you.
; ;using new AutoVarResource;doStuffWithResourceresource; ↓ ↓ ↓ ↓ ↓ ↓ ;try finally
📀 Installation
Make sure babel-plugin-macros
,
is added as "macros"
item in "plugins"
array of your babel config file.
Afterwards just install this package as dev dependency and use it in your code:
npm i -D using.macro
😎 Syntax
The way you import this macro doesn't matter (as long as TypeScript eats it):
;;;;
There are only two options for invoking this macro:
- Near variable declaration
var/let/const varId = using(expresssion);
- As a single expression statement
using(expression);
so that a variable will be created automatically to release it for you.
🔨 Customize
By default when you do
;
you get .delete()
method called on your handles.
If you want to change this behaviour to e.g. call free()
function on your handle,
you can wrap this macro with your own via createUsingMacro()
from 'using.macro/create'
:
// using-ptr.macro.ts # .macro extension matters! See babel-plugin-macros docs;; ; // Pass this noop function type to createMacro<>() for TypeScript support.;
and use it in your code this way:
; ;// stuff ↓ ↓ ↓ ↓ ↓ ↓ ;try finally
create[Function/Method]CallFactory()
are simply two helper
functions. You can actually pass your own destructor codegen function instead:
; // default import is not supported by babel! createUsingMacro
⚠️ Caveats
Unfortunately 'babel-plugin-macros'
doesn't natively support TypeScript macros
in runtime, so you need to build your custom *.macro.ts
to *.macro.js
file,
and put in the same directory as ts
file.
↗️ References
If you are looking for a native using
binding syntax, please support this stage 2 proposal and upvote
this proposition to it.
This macro was originally created for simplifying the usage of
'embind'
C++ object
handles