Trying to use grunt-contrib-requirejs to minify all JS to one file

8.7k views Asked by At

I have the following directory structure (relevant bits only):

app
 - build
   - script.js
 - js
   - lib
     - require.js
     - jquery-1.10.2.js
   - app.js
 - index.html
Gruntfile.js

Gruntfile.js contains the following:

module.exports = function (grunt) {

    var gruntConfig = {
        pkg: grunt.file.readJSON('package.json'),
        requirejs: {
            compile: {
                options: {
                    name: 'app',
                    baseUrl: 'app/assets/js',
                    out: 'app/assets/build/script.js',
                    include:  ['lib/require'],

                    uglify: {
                        // beautify: true,
                        defines: {
                            DEBUG: ['name', 'false']
                        }
                    },

                    paths: {
                        jquery: "lib/jquery-1.10.2"
                    }
                }
            }
        },
    };

    grunt.initConfig(gruntConfig);

    grunt.loadNpmTasks('grunt-contrib-requirejs');

};

app.js contains the following:

require(['jquery'], function ($) {
    // Do stuff
});

How do I set it up so that it copies all the JavaScript needed into build/script.js, not just app.js and require.js when I tell it to (erroring when I try to use jQuery)? I also want to be able to add modules without adding them to my Gruntfile, just by adding them to script.js.

2

There are 2 answers

1
vivek On

You can have a mainConfigFile defined and inside config file have paths to you lib code like this

Contents of gruntfile:

requirejs: {
  compile: {
    options: {
      baseUrl: "app/js/",
      mainConfigFile: app/config.js",
      out: "build/script.js",
      name: "config"
    }
  }
}

Contents of config file:

require.config({
  paths: {
    lib: "<path to>/js/lib",
    jquery: "<path to>/js/lib/jquery-1.10.2.min",
    .
    and particular file required
    .
  }

Requirejs will add the contents of all path files to the optimized code.

0
edrpls On

Try adding this to your options object:

findNestedDependencies: true

This way grunt-contrib-requirejs (actually just requirejs) will find whatever dependencies are listed on your config file.

Hope it works for you.