EzDevInfo.com

grunt-contrib-requirejs

Optimize RequireJS projects using r.js. Grunt: The JavaScript Task Runner

Running Google Closure compiler with grunt

I am trying to create a grunt task to build a javascript project using requirejs with closure compiler as the optimizer. I am using the grunt-contrib-requirejs plugin.

https://www.npmjs.org/package/grunt-contrib-requirejs

Although I haven't explicitly setup the closure compiler, here is the config and the error:

Config:

requirejs:
      compile:
        options:
          sourceMap: true
          baseUrl: "client"
          mainConfigFile: "main.js"
          name: "main.js"
          out: "build/main.js"
          optimize: "closure"
          #generateSourceMaps: true
          closure:
            CompilerOptions: {},
            CompilationLevel: 'SIMPLE_OPTIMIZATIONS'
            loggingLevel: 'WARNING'

Error:

C:\Users\Project>grunt requirejs
Running "requirejs:compile" (requirejs) task
{ [Error: Error: optimizer with name of "closure" not found for this environment

    at Object.optimize.js (C:\Users\Project\node_modules\requirejs\bin\r.js:24771:27)
]
  originalError: [Error: optimizer with name of "closure" not found for this env
ironment] }

Closure is written in java and my project is in nodejs and I'm not sure how to set it up right.


Source: (StackOverflow)

More than 1 requirejs task in grunt for different optimization options

I use r.js to cobble together all the js code in my SPA into 1 file. I use grunt's `grunt-contrib-requirejs' task for this, with the following:

requirejs: {
  compile: {
    options: {
      name: 'app',
      out: 'build/js/app.js',
      baseUrl: 'app',
      mainConfigFile: 'config/main.js',
      preserveLicenseComments: true,
      optimize: "none"
    }
  }
}

I also use a build task that zips the build folder into a zip file for me to send to our company's change management folks.

I would like to have two requirejs tasks - one that uglifies (for sending to CM) and one that doesn't (during development). Is this possible? I tried creating a new task with a different name and grunt yelled at me... should be simple. Is this possible? Are there any reasons not to do this?

Thanks in advance!


Source: (StackOverflow)

Advertisements

requirejs optimizer - need help optimizing our application

We have a large scale javascript application that we are trying to concatenate and minify using grunt-contrib-requirejs. We use the Aura framework. We use bower to pull in dependencies from other repositories into our main application.

Here is our app structure

- app/  
   |  
   |_ main.js  
   |_ index.html  
   |_ css
   |_ bower_components/  
      |_ core/
      |_ widget1/  
          |_ main.js  
          |_ views/  
          |_ models/  
      |_ widget2/  
      |_ extension1/  
      |_ extension2/  
      |_ other third party libraries, etc
- Gruntfile.js
- bower.json

main.js:

requirejs.config({
    shim: {
        ...
    },
    paths: {
       'core': 'bower_components/core/app/main',
       'aura': 'bower_components/aura/dist/',
       'jquery': 'bower_components/jquery/jquery',
       'backbone': ...,
       ... lots of other paths
    }
});
define(['core', 'jquery', 'jqueryui'], function(core, $) {
    // Here we start Aura, which finds our extensions and widgets in
    // bower_components
});  

Our current requirejs task config:

requirejs: {
    compile: {
        options: {
            mainConfigFile: 'app/main.js',
            name: 'main',
            include: ['bower_components/widget1/main', 'bower_components/widget2/main',
                'bower_components/extension1/main', 'bower_components/extension2/main'],
            exclude: ['jquery'],
            insertRequire: ['main'],
            out: 'dist/app.js'
        }
    }
}

This concats our app/main and its dependencies, but when we try to run it, we get errors like:
GET http://www.my-machine:8080/bower_components/underscore/underscore.js 404 (Not Found) even though underscore is a dependency of many of the widgets we include.

We have extensively tried different options in the r.js examples, and read through many stackover flow issues trying to find an answer.
We want advice on how to build this into one minified file with this structure:

UPDATE #2: Correct file structure

- dist/  
    |_ index.html // copied using grunt copy
    |_ css        // copied using grunt copy
    |_ app.js     // Built with grunt requirejs

UPDATE
We have included underscore in our shim which fixed the above error, but we're still getting another error:

Failed to load resource: the server responded with a status of 404 (Not Found)
http://my-machine.com:8080/bower_components/core/app/main.js  

This is included in the minimized file so I don't understand why it can't find that file:

define("bower_components/core/app/main.js", ["aura/aura", "bootstrap"], function(){
...
});

UPDATE #3
The define above came from the file generated by the optimization tool! The original define for that module, core/app/main.js, looks like:

define(['aura', 'bootstrap'], function(Aura) {
    ...
});

Source: (StackOverflow)

Building Durandal with Grunt (R.js + Text)

I would like to use Grunt to build a Durandal project, because Weyland remains completely undocumented and isn't as standard as Grunt.

To do this, the grunt task needs to pull in all the js and html files during optimization, but I am unable to get RequireJS to inline the html files via the text module.

It looks like weyland copies the text files manually, but I can't figure out what it's doing to get requirejs (or almond, in this case), to actually use them. I have seeen this question, but it requires the text modules to be referenced in the define call, which isn't done in Durandal.

My gruntfile for require uses this config

requirejs: {
            build: {
                options: {                  
                    name: '../lib/require/almond-custom', //to deploy with require.js, use the build's name here instead
                    insertRequire: ['main'], //needed for almond, not require
                    baseUrl: 'src/client/app',
                    out: 'build/main-built.js',
                    mainConfigFile: 'src/client/app/main.js', //needed for almond, not require
                    wrap: true, //needed for almond, not require
                    paths: {
                        'text': '../lib/require/text',
                        'durandal':'../lib/durandal/js',
                        'plugins' : '../lib/durandal/js/plugins',
                        'transitions' : '../lib/durandal/js/transitions',
                        'knockout': '../lib/knockout-2.3.0',
                        'bootstrap': '../lib/bootstrap.min',
                        'jquery': '../lib/jquery-1.9.1',
                        'Q' : '../lib/q.min'
                    },
                    inlineText: true,
                    optimize: 'none',
                    stubModules: ['text']               
                }
            }
        }

Source: (StackOverflow)

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

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.


Source: (StackOverflow)

Tell RequireJS to not minify a file

How can I use grunt-contrib-requirejs config OR even r.js Config to not minify specific files.

I can disable minification for all files with optimize: 'none' option. But I don't know how to disable it for a single file.

  options: {                                        
      // Do not minify these files: 
      // 'jquery'
      optimize: 'none', // disables minification for all files
    }

I still want the file to be included in the final merged file (unlike empty: http://requirejs.org/docs/optimization.html#empty ), just not passed into uglify.js


Source: (StackOverflow)

grunt requirejs ignores paths from my mainConfigFile

Project Intro

My project is a single page storefront. The project has multiple modules, and each module contains a set of controller.js, view.js and model.js files, as well as a template.html file. And uses requirejs to manage dependencies.

Problem Statement

I want to use mainConfigFile to provide paths to reference modules in grunt-requirejs. Part of my mainConfigFile's require.config is stored in separate file (base.dependency.config), and require.config.paths are pieced together by underscore at runtime.

base.dependency.config

config = {
    baseDependencyConfig: {
        paths: { ... }
        shim: { ... }
    }
}

main.js

var dependencies = config.baseDependencyConfig;
var basePaths = config.baseDependencyConfig.paths;
var extensionPaths = {
    // extra sets of paths
};

// combine base paths and extension paths at runtime using underscore
var dependencyPaths = _.extend(basePaths, extensionPaths);

dependencies.paths = dependencyPaths;
require.config(dependencies);

// application startup
require(['app', 'eventbus']) {
    // code
}

Error

However, grunt requirejs is ignoring mainConfigFile, grunt requirejs tries to find 'app.js' under root, when in fact, 'app' is defined under require.config paths as

'app': 'modules/base/app/base.app.controller'

my gruntFile:

module.exports = function (grunt) {
    grunt.initConfig({
        // ... other plugin config
        requirejs: {
            options: {
                baseUrl: 'public',
                // the paths for the named modules such as 'app' are defined 
                // in main.js under require.config paths
                name: 'main',
                include: [
                    'app',
                    'cart',
                    'category'
        ],
        out: 'public/build/app-optimized.js',
        mainConfigFile: 'public/main.js',
        findNestedDependencies: true,
        optimizeCss: 'none',
        cssImportIgnore: 'style/style.css, style/mocha.css',
            }
        }
    })
}

my file structure

public
    |--modules/
    |       |--base/
    |       |       |--cart
    |       |       |--category
    |       |               |--category.controller.js
    |       |               |--category.view.js
    |       |               |--category.model.js
    |       |               └-category.template.html
    |       |
    |       └--extension/
    |
    |--style/
    |--image/
    |--main.js <-- main config file
    |--other .js files
  • mainConfigFile, main.js lives in root, along with a few other application startup js files
  • main bulk of application files lives inside modules folder
  • each module folder contains its controller, view and model js file, as well as a template.html file

Edit

the gruntFile worked before, with different mainConfigFile (main.js) setup:

require.config({
    paths: {...}
    shim: {...}
})

// application startup
require(['app', 'eventbus']) {
    // code
}

Source: (StackOverflow)

grunt requirejs 'define is undefined'

I'm trying to optimize RequireJS using GruntJS, using the grunt-contrib-requirejs plugin.

The problem is my code works fine before optimizing it, and then after optimizing it, on the console it says Uncaught ReferenceError: define is not defined.

Here's the Gruntfile.js

module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  grunt.initConfig({
    requirejs: {
        compile : {
            options : {
              name  : 'main',
              baseUrl : ".",
              mainConfigFile : "./main.js",
              out : "./optimized.js",
              preserveLicenseComments: false
           }
        }
}
  })

  grunt.registerTask('default', 'requirejs');

}

Source: (StackOverflow)

Testing JavaScript using grunt

I have to run tests against a JavaScript file using grunt framework.

Just needed any simple example to do this, the target file (/test/filename.js) has dependencies on one more file.


Source: (StackOverflow)

RequireJS Optimizer from mainConfigFile not working

I am using grunt-requirejs and my app structure looks like this:

site/
  dev/
    index.html
    config.coffee
    app.coffee
    etc.
  srv_dev/
    index.html
    config.js
    app.js
    etc.
  dist/
  node_modules/
  Gruntfile.coffee

When I run grunt dev files get compiled to js from coffee among other tasks and copied from dev/ to srv_dev/ and then are served from there.

My grunt dist task does what dev does and then runs a requirejs task, which, I hope, should compile / combine all the main dependancies of my app, but still allow for require(somevar) and define calls to run later on. Basically I have some parts of my single-page app which dont load until the user clicks on the link to it, which fires off a requrire() and define() call.

My current problem seems quite basic... I have set up my requirejs grunt task as follows:

requirejs:
  options:
    baseUrl: './'
    mainConfigFile: 'srv_dev/config.js'
  dist:
    options:
      out: 'dist/script.js'

This throws Error: Error: Missing either a "name", "include" or "modules" option

I have read most of the optimizer docs as well as the example build file and don't understand what is going on with this error. tkellen in this project uses the name option for almond.js -- but I don't think I want to do that, because I need those lazy - loader require() calls. The example build file states: "Just specifying a module name means that module will be converted into a built file that contains all of its dependencies." So that was my next attempt:

requirejs:
  options:
    baseUrl: './'
    name: 'srv_dev/config.js'
  dist:
    options:
      out: 'dist/script.js'

With this I get Error: ENOENT, no such file or directory >> '/Users/user/Desktop/project/site/app.js'

So it finds config.js, but then can't find the paths listed in the config, because it using the baseUrl of the require.js config.

And if I specify the baseUrl of './srv_dev' in the requirejs task config then it cant find my config.js file. I have tried a variety of paths to get this to work with no luck. I think the gruntfile needs to be in the same dir as the config.js file, but thats not how my project is set up.

Thanks Folks !!!

Here is the full text of my config.coffee file

config =

  baseUrl: './'

  paths:
    # require plugins
    text             : '/components/requirejs-plugins/lib/text'
    json             : '/components/requirejs-plugins/src/json'

    # lib
    jquery           : '/components/jquery/jquery'
    bootstrap        : '/components/bootstrap/dist/js/bootstrap'
    lodash           : '/components/lodash/dist/lodash'
    backbone         : '/components/backbone/backbone'
    marionette       : '/components/marionette/lib/backbone.marionette.min'
    handlebars       : '/components/handlebars/handlebars'
    prism            : '/components/customPrism/prism'
    coffeescript     : '/components/coffee-script/extras/coffee-script'

    # app
    app              : '/app/app'
    appSettings      : '/app/appSettings'
    AppController    : '/app/AppController'
    AppRouter        : '/app/AppRouter'

    postMasterRecord : '/posts/postMasterRecord'

    util             : '/scripts/util'
    templates        : '/templates'
    handlebarsHelpers: '/scripts/handlebarsHelpers'

  shim:
    # lib
    bootstrap:
      deps: ['jquery']
    backbone:
      deps: ['lodash', 'jquery']
      exports: 'Backbone'
    marionette:
      deps: ['backbone', 'lodash', 'jquery']
      exports : 'Marionette'
    handlebars:
      exports: 'Handlebars'
    templates:
      deps: ['handlebars']

    # app
    app:
      deps: [
        'marionette'
        'bootstrap'
        'handlebars'
        'templates'
      ]

  # deps: ['app']

require.config(config)

require(['app'])

Source: (StackOverflow)

Shim from grunt-contrib-requirejs not wrapping library

I am using requirejs and configuring my product artifacts, thus combining my libraries and setting up module dependencies between them to get the loading sequence appropriate using the grunt task for requirejs. I have no problem using runtime module injection while in my livereload server which has access to non-combined libraries. For the sake of clarity I have disabled all minification/uglification and turned on a js-beautify.

    requirejs: {
        dist: {
            // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
            options: {
                // `name` and `out` is set by grunt-usemin
                // name: 'App',
                baseUrl: yeomanConfig.app + '/scripts',
                mainConfigFile: yeomanConfig.app + '/scripts/config.js',
                out: yeomanConfig.dist + '/scripts/main.js',
                optimize: 'none',
                // TODO: Figure out how to make sourcemaps work with grunt-usemin
                // https://github.com/yeoman/grunt-usemin/issues/30
                //generateSourceMaps: true,
                // required to support SourceMaps
                // http://requirejs.org/docs/errors.html#sourcemapcomments
                beautify: false,
                removeCombined: false,
                generateSourceMaps: false,
                preserveLicenseComments: false,
                useStrict: true,
                mangle: false,
                compress: false,
                // wrap: true,
                // https://github.com/mishoo/UglifyJS2
            }
        }
    },

I am using Kendo, Angular, and Angular-Keno-UI. I understand Kendo is AMD-module-ready but it doesn't look like Angular-Keno-UI is. I was expecting to create a shim and it be wrapped in the appropriate requirejs define function, however I do not find this to be happening.

    require.config({
        cjsTranslate: true,
        paths: {
            jquery: 'vendor/jquery/jquery',
            'angular-kendo-ui': 'vendor/angular-kendo-ui/build/angular-kendo',
            kendo: 'vendor/kendoui.complete.2013.2.918.trial/js/kendo.all.min',
            angular: 'vendor/angular/angular',
            requirejs: 'vendor/requirejs/require',
            'angular-animate': 'vendor/angular-animate/angular-animate',
            'angular-ui-router': 'vendor/angular-ui-router/release/angular-ui-router.min',
            'angular-resource': 'vendor/angular-resource/angular-resource'
        },
        shim: {
            jquery: {
                exports: '$'
            },
            angular: {
                deps: [
                    'jquery'
                ],
                exports: 'angular'
            },
            'angular-resource': {
                deps: [
                    'angular'
                ]
            },
            'angular-kendo-ui': {
                deps: [
                    'angular',
                    'kendo'
                ]
            },
            'angular-ui-router': {
                deps: [
                    'angular'
                ]
            }
        }
    });

To resolve the lack of module preparation I wrap it myself as such:

    define('angular-kendo-ui', [
        'angular', 
        'kendo'
      ], function (
        angular,
        kendo
      ) {
        < original angular-kendo-ui source >
    });

Have I misunderstood the application of the shims? It would seem I have and it doesn't actually wrap the path defined but rather just points to it if the module is requested (which is fine in dynamic module loading)

During my initial vetting of these technologies I noted SOMEWHERE that there was a way to have requirejs (or one of the asset mutators in my pipeline) automatically wrap modules for me. Anyone have a hint for me, I assume it was requirejs that would wrap modules defined in the config as paths but maybe I was wrong. Below is a printout of tasks being ran:

    Done, without errors.

    Elapsed time
    build                          887ms
    useminPrepare:html             22ms
    concurrent:dist                8s
    autoprefixer:dist              174ms
    requirejs:dist                 19s
    jsbeautifier:dist              2s
    concat:public/styles/main.css  46ms
    concat:public/scripts/main.js  56ms
    cssmin:public/styles/main.css  81ms
    copy:dist                      26ms
    usemin:html                    5s
    usemin:css                     24s

Source: (StackOverflow)

grunt-contrib-requirejs compile gives an error while r.js works manually

I am having problems with running requirejs as a grunt task to compile my js-files. When I run it manually (r.js.cmd -o configfile.js) with the same config file everything seems to work.

It seems that the grunt task is ingoring path definitions and is not capable to find my lib files.

>> Error: ENOENT, no such file or directory
>> '/path/to/project/js/lib.js'
>> In module tree:
>>     module
>>       libs/another-lib

The path should be /path/to/project/js/lib/lib.js. My main js-file (the one in data-main-attribute) has a requirejs.config call with correct path mapping ('lib': 'lib/lib.js'). After that I use them as parameters in a require call which starts the application.

My requirejs task configuration:

requirejs: {
    compile: {
        options: {
            name: "bootstrap",
            baseUrl: "submodule/js",
            mainConfigFile: "submodule/build.js",
            out: "submodule/js/bootstrap-built.js"
        }
    }
}

The only difference between grunt requrejs call and r.js.cmd -o build.js should be the grunt task configuration. They are using the same configuration file after all. What am I doing wrong or is there some kind of issue with paths in grunt-contrib-requirejs?


Source: (StackOverflow)

'no such file' error when using grunt-requirejs compile

Since most issues with require.js build has to do with file structure and relative path reference, I created a repo here: https://github.com/ttback/requirejs-example for easier troubleshoot.

The error is when i run grunt, I will get no such file or directory requirejs-example/src/js/bundle/js/bundle/utils.js

This is due to the wrong baseUrl. I want it to be src/ but I can't set it since it goes to find the dependencies for src/js/bundle/main.js based on my Gruntfile. So the base is at src/js/bundle. The current main.js works with the index.html, if I change the relative path to utils.js from .js/bundle/utils.js to ./utils.js inside main.js, the app wil break.

Is there any way I can make the grunt-requirejs work with what I have?


Source: (StackOverflow)

Requirejs optimization with grunt

I am trying to create a requirejs optimization config with grunt and almond. Here's the config:

requirejs:
      build:
        options:
          almond: true
          dir: 'build'
          appDir: ''
          baseUrl: '../client'
          wrap: true
          include: '../client/main'
          keepBuildDir: true
          paths:
            underscore: 'client/vendor/underscore'
            jquery    : 'client/vendor/jquery'
            backbone  : 'client/vendor/backbone'

Folder Structure:

enter image description here

Error:

C:\Users\User\Documents\Source\Project>grunt requirejs
Running "requirejs:build" (requirejs) task
>> Error: ENOENT, no such file or directory
>> 'C:\Users\User\Documents\Source\Project\build\models\MenuItem.js'
>> In module tree:
>>     ../client/main
Warning: RequireJS failed. Use --force to continue.

Main.js code (written in coffeescript)

requirejs.config(
  baseUrl: "client"
  shim:
    'backbone':
      deps: ['jquery']
      exports: 'Backbone'
    'jquery':
      exports: '$'
    'underscore':
      exports: '_'
  paths:
    jquery: 'vendor/jquery-1.11.0'
    underscore: 'vendor/underscore'
    backbone: 'vendor/backbone'
)

define 'start', ()->
  window.types =
    Models: {}
    Collections: {}
    Views: {}
  null

require ['models/MenuItem', 'views/MenuItem'], (MenuItemModel, MenuItemView)->
  view = new MenuItemView(
    new MenuItemModel(),
    "#app",
    'first'
  )
  view.render();
  null

I want to compile my entire project spread across multiple js files into a single file in a way that requirejs would not be needed. I am trying to do this using almond js but the build task does not look for referenced files relative to the path of referring file. Please help me with the correct configuration.


Source: (StackOverflow)

Can't find a way to optimize with requirejs and grunt the following:

I've this dir structure:

webapp     
  ├──static
  │   ├── app
  │        ├── config.js
  │        ├── frontpage.js
  │        ├── profile.js
  │        └── utils.js
Gruntfile.js

And I'm trying to use grunt-contrib-requirejs to optimize my dependencies for profile and frontpage. Now my config.js looks like:

    require.config({
        {
          baseUrl:"/static/app",
          shim: {
           bootstrap : { "deps" :['jquery'] } ,
           velocity : { "deps" : ['jquery']}
          },
          paths: {
            jquery: "../bower_components/jquery/dist/jquery.min",
            bootstrap : "//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min",
            requirejs: "../bower_components/requirejs/require",
            handlebars: "../bower_components/handlebars/handlebars.min",
            velocity: "../bower_components/velocity/velocity.min"

          },
          packages: []
        });

I tried the following config for grunt-require-config

requirejs: {
          compile: {
            options: {
              appDir: "static/app",
              modules : [
                {
                    name: "profile"                 
                }
              ],
              mainConfigFile: "./static/app/config.js",
              optimize: "none",
              dir: "./static/build/"
            }
          }
        }

but I get this error:

Running "requirejs:compile" (requirejs) task
{ [Error: Error: ERROR: module path does not exist: /static/app/profile.js for module named: profile. Path is relative to: /webapp
 [..]

which is strange, because that path is correct!

I can't find many examples of this around, can anyone help?

UPDATE:

All I needed was to adjust the baseUrl in the Gruntfile.js and I removed appDir. The baseUrl in the requirejs options is now the same as in the config.

requirejs: {
          compile: {
            options: {          
              baseUrl: "static/app",
             /* modules : [
                {
                    name: "profile"

                },
                {
                    name: "frontpage"

                }
              ],*/
              mainConfigFile: "./static/app/config.js",
              optimize: "none",
              dir: "./static/build/"
            }
          }
        }

Source: (StackOverflow)