Skip to content

Clarifying injected paths

Томаш Хамлай edited this page Sep 27, 2016 · 6 revisions

Default behavior

By default gulp-inject only removes each source file's cwd from their respective paths before injecting them. When doing so gulp-inject only matches the full cwd path, so trying to inject gulp.src('../../folder/**/*.js') will inject full paths for each source file, because their paths no longer contain the full cwd path. If one really wants to inject files from a folder higher up in the directory tree a better option is to use gulp.src's cwd option or gulp-inject's relative option (see below).

Example:

A file structure like this:

/project-root
└── src
    ├── app
    │   └── index.js
    └── index.html

And a gulp task like this:

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./src/**/*.js', {read: false})))
  .pipe(gulp.dest('./dist'));

Will inject the following into ./src/index.html when running the task in /project-root (i.e. cwd = /project-root):

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

Removing leading injected path parts

If one wants to remove the /src part from the injected paths there's three ways to accomplish this:

1. Using gulp.src's cwd option:

Note: cwd must be a full path! (for cross platform support use path.join instead of + '/) 2nd note: the glob pattern must now be relative to the ./src folder

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./**/*.js', {read: false, cwd: __dirname + '/src'})))
  .pipe(gulp.dest('./dist'));
2. Using gulp-inject's relative option:

Note: gulp-inject now removes the target file's cwd from each source file's path before injecting it.

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./src/**/*.js', {read: false}), {relative: true}))
  .pipe(gulp.dest('./dist'));
3. Using gulp-inject's ignorePath option:

Note: gulp-inject now removes both each source file's cwd and the given ignorePath (or paths if it's an Array) from their paths before injecting them.

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./src/**/*.js', {read: false}), {ignorePath: 'src'}))
  .pipe(gulp.dest('./dist'));