Use Gulp to wrap javascript files with a IIFE
Asked Answered
L

1

19

I have an angular app that has a lot of .js files. It's boring to add an IIFE to each file and then add 'use strict'.

Is there any way to automate this? I use gulp to run tasks.

Lipcombe answered 26/8, 2014 at 14:31 Comment(0)
F
38

Use the gulp-wrap plugin with a simple template:

var wrap = require("gulp-wrap");

gulp.src("./src/*.js")
    .pipe(wrap('(function(){\n"use strict";\n<%= contents %>\n})();'))
    .pipe(gulp.dest("./dist"));

This will wrap each file's contents with the template:

(function(){
"use strict";
//contents here…
})();

You can also store the template on the filesystem, rather than embedding it in your gulpfile, and call gulp-wrap using wrap({src: 'path/to/template'})

Frolick answered 26/8, 2014 at 15:16 Comment(2)
Good call. I skipped the newlines in the template to keep line numbers consistent when I get errors in the browser. My template was just '(function(){ "use strict"; <%= contents %> })();'Microorganism
Note that there's also gulp-wrap-js that claims to be (contrary to gulp-wrap) compatible with gulp-sourcemaps.Agraphia

© 2022 - 2024 — McMap. All rights reserved.