Home

Awesome

grunt-inject

Grunt task to inject scripts during development. Great for use with LiveReload via grunt-contrib-watch, web inspector remote via grunt-weinre, and Dev Tools snippets. Check out the sample script below.

NPM version Travis Status

Getting Started

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, install this plugin with this command:

npm install grunt-inject --save-dev

Then add this line to your project's Gruntfile.js Gruntfile:

grunt.loadNpmTasks('grunt-inject');

Documentation

Here is a config to inject a script into a single page, and a second config to inject a script into multiple pages. You can use which ever one suits your needs:

inject: {
  single: {
    scriptSrc: 'workflow.js',
    files: {
      'dist/index.html': 'src/index.html'
    }
  },
  multiple: {
    scriptSrc: ['workflow/**.js'],
    files: [{
      expand: true,
      cwd: 'src',
      src: ['**/*.html'],
      dest: 'dist'
    }]
  }
}

Required properties

scriptSrc

Type: String || Array || file glob

The path of the script(s) to be injected into the page.

files

Type: Grunt file configuration

The src HTML files must have the following comment which is replaced by the injected JavaScript:

<!-- inject -->

Sample Script

Here is a sample workflow.js which works together with grunt-contrib-watch with livereload and grunt-weinre with the recommended usage.


// Adds LiveReload script pointing at the client's hostname.
// This is helpful for mobile web development where your desktop might point at localhost while
// your devices point to a local IP address.
document.write('<script src="http://'
 + window.location.hostname
 + ':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')

// Adds the client as a weinre(web inspector remote) debugging target at http://localhost:8082/client/#anonymous
// This is used to debug every mobile browser besides Mobile Safari and Chrome for Android
document.write('<script src="http://' + window.location.hostname + ':8082/target/target-script-min.js#anonymous"><\/script>');

Changelog

0.1.1 - scriptSrc now accepts more types to allow workflow scripts/snippets to be separated into discrete files.

0.1.0 - Multiple script injectons can now be configured in a single task now that the Grunt file configuration is used.

Breaking Changes:

0.0.0 - Initial release.