Gulp inject based on file

121 Views Asked by At

I have this structure

    ├── a
    │   ├── a.html
    │   └── a1.js        
    │   └── a2.js
    ├── b
    │   ├── b.html
    │   └── b1.js
    │   └── b2.js

I want to inject the a1.js & a2.js files to a.html. Same case with b. How can I do that with gulp? I cant find what to write on inject()

    gulp.task('injectRelative', function () {
      gulp.src('./build/**/index.html')
        .pipe(inject(gulp.src('./build/**/*.js', {read: false}), {relative: true}))
        .pipe(gulp.dest(localConfig.buildFolder));
    });
1

There are 1 best solutions below

0
Mark On

There may be ways to do this entirely within gulp-inject but the following is pretty straightforward:

const gulp = require('gulp');
const inject = require('gulp-inject');
const glob = require("glob");
const path = require('path');

// get your target html files as an array of strings
const htmlTargets = glob.sync("./**/*.html");

gulp.task('default', function () {

  htmlTargets.forEach(function (htmlTarget) {

    let directory = htmlTarget.split('/')[1];

    const sources = gulp.src(path.join('./', directory, '*.js'))

    return gulp.src(htmlTarget)
      .pipe(inject(sources))
      .pipe(gulp.dest('dist'));

  });
});