1

I am trying to prepend Javascript to a javascript file using a babel plugin. This is my current babel plugin.

const babel = require("@babel/core")

module.exports = () => {
    return {
        visitor: {
            Program: {
                enter: (path, state) => {
                    const options = state.opts
                    const file = state.file
    
                    if (!options.accept(file.opts.filename)) return
                    path.node.body.unshift(
                        babel.parse(options.prepend).program.body[0]
                    )             
                }
            }
        }
    }
}

This code does work but it does not prepend at the actual top of the file. Here is an example of where it prepends:

Example of where it prepends

Is there any way to change this plugin to actually prepend the javascript at the top?

PowerKuu
  • 63
  • 7
  • Sorry this isn't an answer per-se, but I think you're running into issues with later plugins adding code to the top of the file. I would guess if you re-generated the ast after you make your changes you'd see them at the top of the file, but since other plugins / presets run afterwards they're doing the same "prepend to file" logic you are and it's pushing yours down. – Tim Brown Feb 08 '23 at 03:55
  • Yes i fixed it by removing the transform-es-modules plugin from babel and rewrote everything. – PowerKuu Feb 21 '23 at 12:04

0 Answers0