Implement a DSL
What Are We Building?
In this tutorial, we’ll show how to build a DSL with typedraft.
You can see what we’ll be building here: dsl-debug-demo. We recommend that you check out the repo before continuing with the tutorial.
This DSL allows you to write code such as:
and when you build the project using npm run build, NODE_ENV is set to production so that this block of code will be removed:
if you use npm run dev, NODE_ENV will be dev, and you will get:
After this tutorial, you can implement your own dsl, for example, you can implement "dev" and "production":
Show Me The Code
The interface of a DSL is:
A DSL takes an array of Statement, and return another array of Statement. In this demo:
NODE_ENV is passed in constructor, thus we can use it in Transcribe to decide statements to return.
If we are in dev mode, we will remove just the statement use debug by only returning "the rest of" original statements. When in production, we will remove all statements by returning an empty array.
Learn About AST
We use babel to transform code, and the Statement type comes from @babel/types. So the prerequisite of implementing a DSL is that you have basic knowledge of babel AST.
Reference material can be found in Babel Plugin Handbook.