How to use babel, how to add code at the beginning of each file?

My goal is to fake some requirejs code working through babel. I found that if I add the following: if (typeof define !== "function") { var define = require("amdefine")(module); }to the beginning of each file while working in nodejs, it seems that everything worked out.

Here is the code I wrote that I thought would work or almost work:

function injectDefine(babel) {
    var header = 'if (typeof define !== "function") { var define = require("amdefine")(module); }';

    return new babel.Plugin('amdefine', {
        visitor: {
            Program: {
                enter: function(path, file) {
                    path.unshiftContainer(
                        'body',
                        babel.types.expressionStatement(
                            babel.types.stringLiteral(header)
                        )
                    );
                },
            },
        },
    });
}

require('babel-core/register')({
    stage: 0,
    plugins: [{transformer: injectDefine}],
});

require('../components/button');

A file components/buttonis simply an attempt to verify that a file can load.

Other notes: I am using babel 5, and now I can not update. I also cannot use it .babelrcvery easily right now.

+4
source share
1 answer

1: BABEL_DISABLE_CACHE=1 , . script, , npm run unit, BABEL_DISABLE_CACHE=1 npm run unit .

2: babel.parse . , , babel.parse(header).program.body[0].

:

function injectDefine(babel) {

    var header = 'if (typeof define !== "function") { var define = require("amdefine")(module); }';

    return new babel.Plugin('amdefine', {
        visitor: {
            Program: {
                enter: function(node, parent) {
                    node.body.unshift(
                        babel.parse(header).program.body[0]
                    );
                },
            },
        },
    });
}

require('babel-core/register')({
    cache: false,
    stage: 0,
    plugins: [injectDefine],
});
+2

All Articles