Tan Li Hau

Codemod with babel

March 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
             eg: 
              jsx, flow, typescript, objectRestSpread, pipelineOperator, 
              throwExpressions, optionalChaining, nullishCoalescingOperator, 
              exportDefaultFrom, dynamicImport, ...
            */
            parserOpts.plugins.push(
              'classProperties',
              'classPrivateProperties'
            );
          },
          visitor: {
            // fill in a transformer here
          },
        };
      },
    ],
  });
  await writeFile(filename, code, 'utf-8');
})();

[WIP] I am going to explain how it works and how to use it.


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.