简体   繁体   中英

Remove scripts from index.html through gulp

I'am using gulp in our application, we have 2 flows in Gulpfile.js, one for production and second for development, but I dont want to keep 2 index.html files eg index.html and index.dev. html, I want to have one index.html file, but for production build I have scripts which are no needed eg .

 <!--dev depends -->
    <script src="angular-mocks/angular-mocks.js"></script>
    <script src="server.js"></script>
 <!--dev depends -->

question is: How can I remove something from html through Gulp ?

You can use the gulp-html-replace plugin which is intended for this specific purpose :

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

You could approach is slightly differently: templatize your index.html and use the gulp-template plugin to process the template in your build:

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'));
});

and your index.html could be turned into a template like so:

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

Of course you could write your own plugin / pass-through stream that removes scripts from your index.html but it would require actual parsing / re-writing of the index.html. personally I find the template-based solution easier to put in place and more "elegant".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM