Wednesday, 12 April 2017

How to detect an arbitrary expression in node?

I need to wrap a function call in a function programmatically, for example, I need to transform this...

define('src/libs/require.js', ['src/common/bundle.js'], function (imports) {
    debugger;
    test = imports.test;
    imports.fmtNow();
    self.postMessage({
        method: 'injected',
        message: `${performance.now().fmt()}\tloaded:\tsrc/common/bundle.js`
    });
});

into this...

function inject() {

    define('src/libs/require.js', ['src/common/bundle.js'], function (imports) {
        debugger;
        test = imports.test;
        imports.fmtNow();
        self.postMessage({
            method: 'injected',
            message: `${performance.now().fmt()}\tloaded:\tsrc/common/bundle.js`
        });
    });

}

The define call can be anywhere in the module and the third argument can contain any valid js function definition or expression (that evaluates to a function).

I'm figured out I could use (the HARMONY version) of UglifyJS to do this and I can build an AST and find the expression no problem. Now I have to figure out how to manipulate the AST to add the wrapper and then spit out the modified code.

Is this the right way to go or is there a simpler approach?



via Cool Blue

No comments:

Post a Comment