0

How to properly use my own Babel plugin in Babel's config file?

I am a beginner in writing Babel plugins and I have written a plugin as practice that can extract information from TypeScript files.

And I can use it by parsing the code in my own script, just like this.

const parser = require('@babel/parser')

const { transformFromAstSync } = require("@babel/core")

const fs = require('fs')

const path = require('path')

const myPlugin = require('./plugins')

const sourceCode = fs.readFileSync(path.join(__dirname,"./sourcecode.ts"),{encoding : "utf-8"})

const { code } =  transformFromAstSync(parser.parse(sourceCode,{
    sourceType : "unambiguous",
    plugins : ["typescript"]
}),sourceCode,{
    plugins : [[myPlugin, {
        outputDir : path.resolve(__dirname,'dist'),
        format : "markdown"
    }]]
})

console.log(code)

But when I try to use this plugin in the normal way, just like what we did in the Babel config file.

const path = require('path')

module.exports = function (api) {
    api.cache(true);

    const presets = ["@babel/preset-env"];
    
    const plugins = ["@babel/plugin-syntax-typescript",require('./myPlugin.js')];
  
    return {
      presets,
      plugins
    }

The execution of the above code does not meet my expectations because I found that the @babel/plugin-syntax-typescript has already made some modifications to the source code. When my plugin runs, the code I obtained has many differences in details, such as comments and many ways of writing.

My confusion is regarding a TypeScript plugin.

When I parse source code using @babel/parser, I can correctly set the TypeScript plugin by doing the following:

This will not modify my source code.

parser.parse(sourceCode,{
    sourceType : "unambiguous",
    plugins : ["typescript"]
}

But when I use the @babel/plugin-syntax-typescript plugin, my source code is being modified when the plugin runs.

I understand the rules regarding how Babel invokes plugins and presets, but I don't know how to configure Babel to parse Typescript not generate new code in the configuration file.

If not possible, then I am confused about how we can write a new babel plugin when we cannot control the impact of other plugins and presets on the source code. If a previous plugin has already modified the source code, then the code obtained by our plugin may not meet our expectations.

Any help and advice will be appreciated.

Eric-Guo
  • 3
  • 2

0 Answers0