javascriptgulpgulp-inject

how configure relative file path to dist folder on gulp-inject?


I have a issue when inject resources into the index.html with gulp-inject.

I have the following streams for app styles, vendor js code and app js code:

// Vendor JS code
var vendorStream = gulp.src(mainBowerFiles({
      paths: {
        bowerDirectory: config.bowerDir
      },
      checkExistence: true
  }))
  .pipe(concat('vendors.js'))
  .pipe(gulp.dest(config.bowerLibDist))
  .pipe(size({
      title:"Vendor JS code"
  }));

// JS App Code
var jsStream = gulp.src(config.jsSrcPath)
  .pipe(concat('app.js'))
  .pipe(uglify())
  .pipe(gulp.dest(config.jsDistFolder))
  .pipe(size({
      title:"App js code"
  }));

// SASS App Code
var cssStream = gulp.src(config.sassSrcPath)
    .pipe(sass({
      outputStyle: 'compressed'
    })
    .on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(gulpIf(config.production, cssnano()))
    .on("error", notify.onError(function (error) {
      return "Error: " + error.message;
    })).pipe(gulp.dest(config.cssDistFolder))
    .pipe(size({
      title:"Styles"
    }));

What I want to do is take the index.ml inject these resources and place them in the dist directory throught the following task:

gulp.task('inject', function() {
   return gulp.src('index.html', {cwd: './app'})
        .pipe(inject(es.merge(vendorStream, jsStream, cssStream)))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest(config.distFolder));
});

This works correctly, but the problem is that the path also includes the dist directory. This is the publishing base directory:

// Starts a server using the production build
gulp.task('server', ['build'], function () {
  connect.server({
    root: './dist',
    hostname: '0.0.0.0',
    port: 90
  });
});

How could I configure gulp-inject so that instead of

<script src="/dist/js/app.js"></script>

be

<script src="js/app.js"></script>

thanks :)


Solution

  • One of the ways is to use transform function.

    gulp.task('inject', function() {
      return gulp.src('index.html', {cwd: './app'})
                 .pipe(inject(
                     es.merge(vendorStream, jsStream, cssStream),
                     { 
                         transform: function( filepath, file, index, length, targetFile ) {
                           return inject.transform.call(inject.transform, filepath.replace(/\/dist\//, ""), file, index, length, targetFile);
                         }
                     }
                 ))
                 .pipe(htmlmin({collapseWhitespace: true}))
                 .pipe(gulp.dest(config.distFolder));
    });
    

    You can keep also the initial transform function if you only want to change the filename.