使用Gulp用IIFE包装javascript文件

Pap*_*ord 19 iife angularjs gulp

我有一个有很多.js文件的角度应用程序.向每个文件添加一个IIFE然后添加是很无聊的'use strict'.

有没有办法自动化这个?我用gulp来运行任务.

Ove*_*ous 37

使用gulp-wrap插件用一个简单的模板:

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

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

这将使用模板包装每个文件的内容:

(function(){
"use strict";
//contents here…
})();
Run Code Online (Sandbox Code Playgroud)

您还可以将模板存储在文件系统上,而不是将其嵌入到gulpfile中,然后gulp-wrap使用调用wrap({src: 'path/to/template'})

  • 好决定.当我在浏览器中出现错误时,我跳过模板中的换行符以保持行号一致.我的模板只是`'(function(){"use strict"; <%= contents%>})();'` (4认同)

小智 8

gulp-iife插件是为解决您的问题而制作的.是一篇关于它的文章.