Gulp - does anyone know how to cache bust a js file?

百般思念 提交于 2019-12-10 12:28:18

问题


Gulp - does anyone know how to cache bust a js file?

I'm using gulp, angular2 and html.

Current gulp file with an attempt of cache busting:

'use strict';

const gulp = require('gulp');
const ts = require('gulp-typescript');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
var htmlreplace = require('gulp-html-replace');
var addsrc = require('gulp-add-src');
var cachebust = require('gulp-cache-bust');

// See this article: http://caveofcode.com/2016/03/gulp-tasks-for-minification-and-concatenation-of-dependencies-in-angularjs/

gulp.task('app-bundle', function () {
  var tsProject = ts.createProject('tsconfig.json', {
      typescript: require('typescript'),
      outFile: 'app.js'
  });

  var tsResult = gulp.src([
    'node_modules/angular2/typings/browser.d.ts',
    'app/**/*.ts'
  ])
    .pipe(ts(tsProject));

  return tsResult.js.pipe(addsrc.append('config-prod.js'))
                    .pipe(concat('app.min.js'))
                    .pipe(uglify())
                    .pipe(cachebust({type: 'timestamp'}))
                    .pipe(gulp.dest('./dist'));

});

gulp.task('vendor-bundle', function() {
    gulp.src([
            'node_modules/es6-shim/es6-shim.min.js',
            'node_modules/systemjs/dist/system-polyfills.js',
            'node_modules/angular2/bundles/angular2-polyfills.js',
            'node_modules/systemjs/dist/system.src.js',
            'node_modules/rxjs/bundles/Rx.js',
            'node_modules/angular2/bundles/angular2.dev.js',
            'node_modules/angular2/bundles/http.dev.js'
        ])
        .pipe(concat('vendors.min.js'))
        .pipe(uglify())
        .pipe(cachebust({type: 'timestamp'}))
        .pipe(gulp.dest('./dist'));
});

gulp.task('html-replace',[ 'app-bundle', 'vendor-bundle' ], function() {
  gulp.src('index.html')
    .pipe(htmlreplace({
        'vendor': 'vendors.min.js',
        'app': 'app.min.js'
    }))
    .pipe(gulp.dest('dist'));
});

回答1:


gulp-cache-bust only appends a query string to asset references. It doesn't rename or change the assets themselves in any way.

That means applying cachebust() to your .js files makes no sense. You need to apply it to the HTML that references the .js files:

gulp.task('html-replace',[ 'app-bundle', 'vendor-bundle' ], function() {
  gulp.src('index.html')
    .pipe(htmlreplace({
      'vendor': 'vendors.min.js',
      'app': 'app.min.js'
    }))
    .pipe(cachebust({type: 'timestamp'}))
    .pipe(gulp.dest('dist'));
});


来源:https://stackoverflow.com/questions/37006340/gulp-does-anyone-know-how-to-cache-bust-a-js-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!