Search code examples
grailsjavascriptgrails-plugin

How to properly include JS libs inside a Grails app?


I'm writing my first Grails (2.3.6) app and need to use the following libraries:

I would like to configure these libraries from inside a web-app/js/application.js file. I'm not sure if I should:

  • Manually add the libraries to my web-app/js/ directory, and then import them as <script> elements from inside my GSP (see below); or
  • Pull them in from BuildConfig.groovy.

With the former approach:

// Inside index.gsp:
<body>
    <script type="text/javascript" src="${resource(dir: 'js', file: 'signals.min.js')}" />
    <script type="text/javascript" src="${resource(dir: 'js', file: 'crossroads.min.js')}" />
    <script type="text/javascript" src="${resource(dir: 'js', file: 'hasher.min.js')}" />
    <script type="text/javascript" src="${resource(dir: 'js', file: 'application.js')}" />
</body>

With the latter approach:

// Inside BuildConfig.groovy:
plugins {
    runtime: ":signals:???"
    runtime: ":crossroads:???"
    runtime: ":hasher:???"
}

Which way is the right way to go with Grails, and why? And, if the latter approach is the generally-accepted method, what values do I need for each runtime entry?


Solution

  • Personally I would only go the plugin route if you think these libraries would be a good fit for the community and you want to maintain them. It seems you should either be using the resource plugin as mentioned or the asset-pipeline plugin.

    Personally I would definitely go with the asset pipeline plugin instead of resources. It will be the default in 2.4 and IMHO way easier and faster to use. Lots of other plugins already integrate with it, and it is dead simple to use. You can also add the full non minified versions of the libraries so you have access to them in development for debugging and when you war your project up the plugin will automatically minify and bundle them for you.

    1) Add your libraries to /assets/js/. 2) Add this to application.js

    //This is a javascript file with its top level require directives
    //= require signals.js
    //= require crossroads.js
    //= require hasher.js
    //= require_self
    
    console.log("This is my javascript manifest");
    

    3) Add the asset to your page or layout

    <head>
        <asset:javascript src="application.js"/>
    </head>
    

    http://grails.org/plugin/asset-pipeline