ya.teck
ya.teck

Reputation: 2336

RequireJS optimizer prepend

I am looking for a way to prepend some information to minimized file.

I've found the option here, but it doesn't useful for me because uglifier runs after the wrapper code has been added.

Upvotes: 0

Views: 133

Answers (1)

Rob W
Rob W

Reputation: 349252

You could assign a function to the out key to post-process the file. By setting this option, the result will not automatically be written to a file, so you have to do that yourself. For example:

({
    // Let's optimize mainApp.js
    name: "mainApp",
    optimize: "uglify",
    out: function(text) {
        // Transform the compiled result.
        text = '// Stuff to prepend \n' + text;

        var filename = 'outputfile.js';
        // By default, the name is resolved to the current working directory.
        // Let's resolve it to the directory that contains this .build.js:
        filename = path.resolve(this.buildFile, '..', filename);
        // Finally, write the transformed result to the file.
        file.saveUtf8File(filename, text);
    }
})

Note: In the previous snippet, file.saveUtf8File is an internal RequireJS API and path is the path module imported from Node.js standard library (only if you run r.js with Node.js, and not e.g. with Rhino or in the browser).

If you save the previous as test.build.js, create an empty file called mainApp.js and run `r.js -o test.build.js, then a file called "outputfile.js" will be created with the following content:

// Stuff to prepend 
define("mainApp",function(){});

Upvotes: 2

Related Questions