从index.html通过gulp删除脚本

Nar*_*yan 7 javascript angularjs gulp

我在我们的应用程序中使用gulp,我们在Gulpfile.js中有2个流程,一个用于生产,第二个用于开发,但我不想保留2个index.html文件,例如index.html和index.dev.html,我想要一个index.html文件,但对于生产版本,我有不需要的脚本,例如.

 <!--dev depends -->
    <script src="angular-mocks/angular-mocks.js"></script>
    <script src="server.js"></script>
 <!--dev depends -->
Run Code Online (Sandbox Code Playgroud)

问题是:如何通过Gulp从html中删除某些内容

Del*_*ite 10

您可以使用专门用于此特定目的的gulp-html-replace插件:

https://www.npmjs.org/package/gulp-html-replace


pko*_*rce 6

你可以采用稍微不同的方法:模板化你的index.html并使用gulp-template插件来处理你的构建中的模板:

var template = require('gulp-template');

//production task 
gulp.task('prod', function () {
    return gulp.src('src/index.html').pipe(template({
        scripts : []
    })).pipe(gulp.dest('dist'));
});


//dev task
gulp.task('prod', function () {
    return gulp.src('src/index.html').pipe(template({
        scripts : ['angular-mocks/angular-mocks.js', 'server.js']
    })).pipe(gulp.dest('dist'));
});
Run Code Online (Sandbox Code Playgroud)

index.html可以把它变成这样的模板:

<% _.forEach(scripts, function(name) { %><script src="<%- name %>" type="text/javascript"></script><% }); %>

当然,您可以编写自己的插件/传递流,从index.html中删除脚本,但这需要对index.html进行实际的解析/重写.我个人认为基于模板的解决方案更容易实施,更"优雅".