2

I'm in need of an organization system for my JavaScript code Drupal. Currently, I've got it inside a folder in my theme's directory: "sites/all/themes/mytheme/js". I've looked at using Grunt.js, and wondering how I might implement it into my website. How would it help me?

Can it help organize large JavaScript files?

Could it help improve the speed of my website?

1
  • Sorry to have to close this but it's completely off topic here - setting up grunt isn't related to Drupal in any way, the answer is the same for every type of website - you have some files in some folders, and you run some tasks on them. This would be a decent question for SO, but if wager it's already been asked and answered over there before. If there's a Drupal specific discipline involved here, please update the question and flag for reopening. Many thanks
    – Clive
    Commented Sep 12, 2014 at 7:44

1 Answer 1

2

I started using Grunt.js by reading their easy to follow tutorial. Then, I created a Gruntfile.js inside of my theme’s js directory “sites/all/themes/mytheme/js/Gruntfile.js”:

  module.exports = function(grunt) {
    grunt.initConfig({
       pkg: grunt.file.readJSON('package.json'),
       concat: {
          main: {
             src: [
                'src/*.js',
             ],
             dest: 'production.js'
          }
       },
       uglify: {
          build: {
             files: {
                'production.min.js': 'production.js',
             }
          }
       },
       jshint: {
          files: ['Gruntfile.js', 'src/*.js'],
          options: {
             globals: {
                jQuery: true,
                console: true,
                module: true,
                document: true
             }
          }
       },
       watch: {
          files: ['src/*.js'],
          tasks: ['concat', 'jshint', 'uglify']
       }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');

    grunt.registerTask('test', ['concat', 'jshint']);
    grunt.registerTask('default', ['concat', 'jshint', 'uglify']);
  };

My Gruntfile does 3 things for me (right now):

  1. Combines smaller, more manageable files inside src/ into one file.
  2. Checks for errors in my compiled file.
  3. Compresses my file when I’m ready for production.

All I have to do is run grunt watch from the terminal and whenever one of the files inside src/ is changed my production.js file is updated and compressed. When I’m all done debugging I just change the following in my .info file:

scripts[] = js/production[.min].js

This results in faster page loads because only one (smaller) request is being performed as opposed to many uncompressed file requests.

Not the answer you're looking for? Browse other questions tagged or ask your own question.