Search code examples
javascriptgulpbrowserifybundling-and-minification

Preprocessing with browserify?


How can I preprocess a function call with browserify?

In a large js file, at one point, I need to pass a JSON object to a variable but this JSON object may only be created by a function call:

var myvar = Ractive.parse('mytemplate.html');

If I write this function call like so, this line of code is appeared in the bundle.js file as is. I simply want something like:

var myvar = THIS_WILL_RUN_WHILE_BROWSERIFYING(Ractive.parse('mytemplate.html'));

so in bundle.js I expect to see something like:

var myvar = [{myobj:4},{x:1,y:2}];

How can I make this happen with browserify (with Gulp)?


Solution

  • Browserify allows you to create custom transforms, there is a good example of how to create transforms at the following link.

    https://github.com/substack/browserify-handbook#transforms

    The example of doing a replace of the $CWD with process.cwd(), appeared to be a good starting point for the OP to create the transform required.

    In case of potential future dead links, here is the example.

    var through = require('through2');
    
    module.exports = function (file) {
        return through(function (buf, enc, next) {
            this.push(buf.toString('utf8').replace(/\$CWD/g, process.cwd()));
            next();
        });
    };