angularjsgulpgulp-inject

gulp-inject is not able to inject js file in index.html


My directory structure is as follows:

|- app
   |- bower_components
   |- css
   |- img
   |- js
   |- scss
   |- template
|- node_modules
|- gulpfile.js
|- package.json
|- .bowerrc
|- bower.json

Now my gulpfile.js is as shown below:

gulp.task('index', function() {
    var target = gulp.src('./app/index.html'); 
    var sources = gulp.src(['app/js/**/*.js'], { read: false });

    return target.pipe(inject(sources))
        .pipe(gulp.dest('app/js'));
});


gulp.task('default', function(callback) {
    runSequence(['sass', 'browserSync', 'index'], 'watch',
        callback
    );
});

My index.html file is as shown below:

<!DOCTYPE html>
<html>

<head>
    <title>kisanApp</title>
    <!-- inject:css -->
    <!-- endinject -->
</head>

<body ng-app="kisanApp">
    <ng-view></ng-view>
    <!-- inject:js -->
    <!-- endinject -->
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
</body>

</html>

But somehow my js files are not added in index.html via gulp. So is there anything wrong with the path?


Solution

  • Try adding var inject = require('gulp-inject'); and var gulp = require('gulp'); to the top of your gulpfile.

    And then take another look at your sources and gulp.dest:

    var sources = gulp.src(['./app/js/**/*.js'], { read: false });

    You will need the proceed ./ before app.

    EDIT:

    Use relative true to deal inject files from a folder higher up in the directory tree

    var sources = gulp.src(['./app/js/**/*.js'], { read: false }, {relative: true});