Sergio Sanchez Sergio Sanchez - 1 year ago 162
Javascript Question

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
title:"Vendor JS code"

// JS App Code
var jsStream = gulp.src(config.jsSrcPath)
title:"App js code"

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

What I want to do is take the 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}))

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 () {
root: './dist',
hostname: '',
port: 90

How could I configure gulp-inject so that instead of

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


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

thanks :)

Answer Source

One of the ways is to use transform function.

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download