Codemod with babel

March 13, 2019(Last updated: September 13, 2019)

A general template that I used:

const babel = require('@babel/core');
const { promisify } = require('util');
const { writeFile } = promisify(require('fs').writeFile);

(async function() {
  const { code } = await babel.transformFileAsync(filename, {
    plugins: [
      function() {
        return {
          manipulateOptions(opts, parserOpts) {
             add to parserOpts.plugins to enable the syntax
              jsx, flow, typescript, objectRestSpread, pipelineOperator, 
              throwExpressions, optionalChaining, nullishCoalescingOperator, 
              exportDefaultFrom, dynamicImport, ...
          visitor: {
            // fill in a transformer here
  await writeFile(filename, code, 'utf-8');

[Updated on 2019-09-13]

I have written a step-by-step guide on how to write a babel transformation plugin.

The only difference in this template than the guide is that there’s this manipulateOptions where you can add additional parser options to enable ES2015+ syntax.

Thank you for your time reading through this article.
It means a lot to me.

If you like what you have just read,
Tweet about it so I will write more related articles;
If you disagree or you have opinions about this article,
Tweet about it too so I can take your suggestions and improve on it.