2

I'm using the RequireJS optimiser to minify and concatenate my code. At the moment r.js doesn't minify a lot of my scripts because of the nested dependencies.

I want to include nested dependencies for:

  • All dependencies inside: 'js/services'
  • All nested dependencies for a list of specific JavaScript files

Note: I do realise that there is the option findNestedDependencies: true but this looks for absolutely every dependency across all JavaScript files in the app where as I only want to do this for certain JavaScript files and folders as I have a set of files which are always used on every page/view.

My current build file looks like:

  ({
    baseUrl: '../static/js',
    mainConfigFile: '../static/js/main.js',
    name: 'main',
    out: '../static/js/scripts.min.js',
    paths: {
        requireLib: 'vendor/require/require.min'
    },
    include: 'requireLib'
})

I have been following this tutorial to get the optimiser running: http://www.youtube.com/watch?v=m6VNhqKDM4E

kryger
  • 12,906
  • 8
  • 44
  • 65
Malcr001
  • 8,179
  • 9
  • 44
  • 57

1 Answers1

7

You can use include to specify all dependencies you want to force into the output file:

// ...
include: ['requireLib', 'js/services/dep1', 'js/services/dep2'],
// ...

I don't think there's a way to include entire folder (something like "js/services/*"), though.


Since in my project I had many dynamic dependencies I wanted to include in the output I ended up creating an "js/services/_all.js" module which lists files in its directory, for example:

define([
    './dep1',
    './dep2'
  ],
  function () {
    // this module imports all modules from current folder so 
    // there's no need to list every single file in the build config
  });

and then configuring r.js with:

// ...
include: ['requireLib', 'js/services/_all'],
// ...
kryger
  • 12,906
  • 8
  • 44
  • 65
  • Thanks. I understand the first option but I don't really understand the second example. Is the module a separate file featured within each folder that lists all the files you would like to be included in the minified code? – Malcr001 Oct 12 '13 at 23:17
  • Yes, in the second part I just wanted to share a pattern I've used to avoid listing multiple tiny modules in my build file to keep it readable and maintainable. Depends on how many imports you have in your "js/services"; if not more than 10-15 there's probably no need for hacks like this one. – kryger Oct 12 '13 at 23:47
  • Thanks for the help. The second option worked for me (I had some strange problems using the first option). I have a similar question but instead this time creating separate (concatenated and minified) scripts for sections of the website. I have posted a separate question here. I'd appreciate it if you could take a look: http://stackoverflow.com/questions/19345796/requirejs-optimiser-create-minified-groupings-of-scripts-for-sections-of-the-s – Malcr001 Oct 13 '13 at 13:32