javascriptgruntjsrequirejsr.jsgrunt-contrib-requirejs

Requirejs optimizer and locale setting that is set dynamically


I am using requirejs optimizer (r.js) through grunt and here is my requirejs config :

requirejs.config
  baseUrl: '/scripts'
  locale: window.localStorage.getItem('locale') || null
  ...

The thing is that the grunt r.js plugin (https://github.com/gruntjs/grunt-contrib-requirejs) throw an error everytime I try to use a variable inside my requirejs config.

The main config file cannot be used because it cannot be evaluated correctly while running in the optimizer. Try only using a config that is also valid JSON, or do not use mainConfigFile and instead copy the config values needed into a build file or command line arguments given to the optimizer.

Have you managed to use a variable as a locale and r.js at the same time ?


Solution

  • Your locale setting acquires a real value only at runtime. For parts of RequireJS' config that can only be given values at runtime, what I do is:

    1. Just call require.config (or requirejs.config) once with the information which is static. The config does not contain any variables. I point r.js to this static information.

    2. At runtime, I have at least one additional call to require.config that sets those values that are to be computed. RequireJS combines multiple calls to require.config into one configuration.

    r.js will only use the first configuration it recognizes in a file. So you may be able to just split your single requirejs.config call into a static and dynamic part and leave them in the same file.