Mahesh
Mahesh

Reputation: 141

how to inject javascript at header and body using gulp

I want to inject javascript library inside head tag and my customized and my own code at body using GULP.

For Example:

<html>
    <head>
      <!-- injectJS -->
         <script src="jquery.js">
         <script src="d3.js">
      <!-- injected -->
    </head>

    <body>
      <!-- injectJS -->
         <script src="index.js">
      <!-- injected -->
    </body>
</html> 

Upvotes: 0

Views: 948

Answers (1)

Simon Wicki
Simon Wicki

Reputation: 4059

I've been using gulp-template to do exactly this. Your index.html would then have to be adjusted. e.g.:

<% scripts.forEach( function ( file ) { %>
    <script type="text/javascript" src="<%= file %>" inline></script>
<% }); %>

In this example your gulpfile task would look something like:

gulp.task('index', () =>
    gulp.src('src/index.html')
        .pipe(template({scripts: ['script.js', 'another-one.js']}))
        .pipe(gulp.dest('dist'))
    );

Another way to achieve this would be using gulp-inject. I prefer gulp-template though.

Upvotes: 1

Related Questions