- author: CodeDonor
Using the ES Build Service: A Beginner's Guide to Transpiling with ES Build
If you're interested in transpiling with ES Build, you're in luck! The ES Build service is available inside of On Click, and in this article, we'll take you through how you can use it.
Removing the Console Log
The first step we need to take before transpiling our code is to remove the console.log.
Using the Ref and Transform
Once the console log is removed, we can do a ref.current.transform. The transform function is responsible for transpiling our code. It will not do any bundling or joining up of any different modules or handle import statements, but simply transpile the code.
Adding Arguments to Options
The first argument to transform is the code that we want to transpile, so we'll use our input as the first argument. The second argument is going to be a couple of options to use during the transpiling process. First, it's important to add an option of 'loader' which tells ES Build what type of code we are providing. ES Build can handle different types of code such as JavaScript, JavaScript with JSX, and TypeScript. We'll say that this is going to be JavaScript with JSX inside of it by providing 'JSX' as a string.
Setting the Target to ES 2015
Additionally, we need to put in a target of ES 2015. This is used for the transpiling process, and ES Build can do that transpiling stuff. It will handle Advanced or fancy JavaScript syntax, like spread syntax inside of an object, or async/await stuff. This target right here is going to specify what options we want ES Build to assume that it needs to transpile.
Asynchronous Nature of the Transform Operation
The entire transform operation is asynchronous in nature, so it's important to mark the enclosing function as async and add an await right there. Once transpiling is done, we want to assign the result to a variable called 'result'.
Viewing Result
Once we get the result object, we can see that it has any warnings that came out, a map for a source map, and code that is the transpiled code. We'll take that code and use it to update our code piece of state. After transpiling, we can then update the code's Piece of state, which will cause our component to render, and we should show that code inside the pre-element.
Testing
We can now do a test. Write in some amount of JSX and submit; we can see that the transpiled code shows up inside the pre-element.
Bundling
ES Build is handling transpiling really well, but we still have to make sure that we're able to do some bundling too. If we put in an import statement, it is not really handled well, so we need to add in some additional code to make sure that we can deal with bundling, too.
Conclusion
ES Build makes transpiling a breeze, and bundling is also achievable with additional code. If you're a beginner looking to get started with transpiling, ES Build is a great place to start.