Question

I am writing my first Yeoman generator. For the index.html page I am referencing the hosted jQuery file on Google with a local fallback. I am using Bower to fetch the latest version of jQuery. Therefore currently my jQuery reference looks like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="assets/bower_components/jquery/jquery.min.js"><\/script>')</script>

This is not ideal as every time this generator is used, the user would have to check which jQuery version Bower fetched, then update the version section in the hosted link with the same version number.

Is there a way to automatically fetch the version number and update the hosted url, presumably using Grunt?

Note: I am not looking for the link for the latest hosted version and I don't want to specify which jQuery version for Bower to fetch as I want it to be the most recent at the time of creation.

Was it helpful?

Solution

Yes, have a look at grunt-replace. Here's a sample config that would replace the link:

    replace: {
        options: {
            patterns: [{
                match: '/@jQueryCDN/g',
                replacement: function() {
                    var jQconf = grunt.file.readJSON('bower_components/jquery/bower.json');
                    return '//ajax.googleapis.com/ajax/libs/jquery/' + jQconf.version + '/jquery.min.js'
                },
                expression: true
            }]
        },
        files: {
            src:  'static/index.html',
            dest: 'build/index.html'
        }
    }

Then just use @jQueryCDN where you want the path to be inserted. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top