Codemod with babel

(Last updated: )

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.

I would appreciate if you tweet about it.