Requirejs optimized file is not executed - requirejs

I am seriously missing some vital element on how to use the r.js optimiser. This is probably a trivial answer for many, but I can for the life of me not figure out the problem.
I've set up my environment using a grunt task to build an optimised file. The optimised file is built and dependencies seems to resolve correctly, but the code in my mainfile is never executed.
I've created a minimal environment to help you help me where there is pretty much only the Gruntfile, the mainfile and some dependencies (jquery, almond).
My project structure is:
require_this/
│
├──Gruntfile.coffee
│
└──src/
│
├──index.html
│
├──bower_components/(jquery,almond,requirejs)
│
└──app/
│
└──main.js
Gruntfile:
module.exports = (grunt) ->
'use strict'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
settings:
distDirectory: 'dist'
srcDirectory: 'src'
tempDirectory: '.temp'
allFile: 'main.js'
clean:
working: ['<%= settings.tempDirectory %>', '<%= settings.distDirectory %>']
finished: ['<%= settings.tempDirectory %>']
copy:
app:
files: [
cwd: '<%= settings.srcDirectory %>'
src: '**'
dest: '<%= settings.tempDirectory %>'
expand: true
]
requirejs:
scripts:
options:
baseUrl: '<%= settings.tempDirectory %>'
mainConfigFile: '<%= settings.tempDirectory %>/app/main.js'
optimize: 'none'
logLevel: 0
findNestedDependencies: true
name: 'main'
include: ['requireLib']
paths:
'main': 'app/main'
'requireLib': 'bower_components/almond/almond'
out: '<%= settings.distDirectory %>/<%= settings.allFile %>'
processhtml:
your_target:
files:
'dist/index.html': '.temp/index.html'
grunt.loadNpmTasks 'grunt-processhtml'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-copy'
grunt.loadNpmTasks 'grunt-contrib-requirejs'
grunt.registerTask 'build', [
'clean:working'
'copy:app'
'requirejs'
'processhtml'
]
index.html:
<!DOCTYPE html>
<head>
<!-- build:js main.js -->
<!-- The line below will be changed to <script src="main.js"></script> after processhtml -->
<script src="bower_components/requirejs/require.js" data-main="app/main.js"></script>
<!-- /build -->
</head>
<body>
</body>
main.js
require.config({
baseUrl: './',
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
define([
'jquery',
], function ($) {
console.log('changing html');
$('body').append('<div>Hello World</div>');
});
After completing the build task, my dist directory will contain index.html and main.js file.
The dist/main.js file will look like:
/*almond stuff*/
/*jquery stuff*/
require.config({
baseUrl: './',
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
define('main',[
'jquery',
], function ($) {
console.log('changing html');
$('body').append('<div>Hello World</div>');
});
Using a static fileserver against the uncompressed files works as expected. When using the build files, nothing is logged and nothing is added to the html even though the optimised file is loaded.
I suspect the answer is similar to Why is my RequireJS ignoring the code in my optimized main.js?, (some module name mismatch?) but I did not understand this well enough to fix my own problem.
Help is greatly appreciated!

The optimized version simply defines module main but it is never executed because it is never required. I'm not sure why is main executed in the non-optimized version.
The main.js could have rather looked like:
require.config({
baseUrl: './',
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
// use require instead of define here
require([
'jquery',
], function ($) {
console.log('changing html');
$('body').append('<div>Hello World</div>');
});
the difference is that instead of defining a module this code requires jquery and passes it to the anonymous function, which is executed right away. It doesn't look like your app actually relied on that code being available as a module (the function doesn't return anything), so this change should be sufficient.

Related

RequireJS baseUrl and multiple optimized files

I've separated out my 3rd party libraries from my app code and grouped them all together into a vendor.js file for requirejs to pull in. In my build.js file, I'm using the modules syntax to optimize my main application, excluding the vendor scripts, and to optimize the vendor.js file. The only issue I'm having is when my compiled main module requests vendor, it's getting the baseUrl from the config file and so doesn't load the optimized vendor.js file. My build.js file looks like this:
({
baseUrl: "js",
dir: "build",
mainConfigFile: "js/main.js",
removeCombined: true,
findNestedDependencies: true,
skipDirOptimize: true,
inlineText: true,
useStrict: true,
wrap: true,
keepBuildDir: false,
optimize: "uglify2",
modules: [
{
name: "vendor"
},
{
name: "main",
exclude: ["vendor"]
}
]
})
And my main.js file looks like this:
requirejs.config({
baseUrl: "js",
paths: {
jquery: 'vendor/jquery/jquery-2.1.3.min',
bootstrap: 'vendor/bootstrap/bootstrap.min',
handlebars: 'vendor/handlebars/handlebars-v2.0.0',
backbone: 'vendor/backbone/backbone-min',
underscore: 'vendor/lodash/lodash.underscore',
marionette: 'vendor/marionette/backbone.marionette.min',
models: 'common/models',
collections: 'common/collections'
}
});
define(['module', 'vendor'], function(module) {
var configPath = "config/config." + module.config().env;
require([configPath, 'app', 'jquery'], function(config, Application, $) {
$(function() {
// Kick off the app
Application.start(config);
});
});
});
All development is done in the js folder, and my build.js file is outside that folder. The optimized files end up in build, a sibling to js, but when I include my main file like this:
<script data-main="build/main" src="js/vendor/require/require.max.js"></script>
It ends up loading js/vendor.js for that define() call. What am I missing here? How can I tell the optimized main file to load build/vendor.js instead, yet allow the unoptimized version to still load js/vendor.js?
Ok, I figured this out. It was simple, really, just a case of too much configuration. When you load your script using data-main, the baseUrl is set relative to that file. So, if I specified js/main, the baseUrl would be js. But, since I explicitly specified baseUrl in the config block of main.js, that gets overridden, both in development and production. By removing baseUrl: "js" from main.js, everything works as expected. The development build loads everything relative to js and the production build loads everything (vendor.js) relative to build when I change data-main to build/main. Hope this helps somebody else someday.
requirejs.config({
paths: {
jquery: 'vendor/jquery/jquery-2.1.3.min',
...
}
});
// 'vendor' is loaded relative to whatever directory main.js is in
define(['module', 'vendor'], function(module) {
...
});

requirejs optimizer doesn't generate '.js' version of the text resource

In my project I use yeoman (1.0.6). In a fresh webapp copy installed requirejs-text plugin to include template.html.
main.js
require.config({
paths: {
jquery: '../bower_components/jquery/jquery',
text: '../bower_components/requirejs-text/text'
}
});
require(['jquery', 'text!../templates.html'], function ($, templates) {
....
After building and optimizing a whole project, I expect to have generated templates.js file instead of templates.html ( added
"optimizeAllPluginResources: true" as described here )
Gruntfile.js ( won't paste all code, just optimization settings )
....
requirejs: {
dist: {
options: {
baseUrl: '<%= yeoman.app %>/scripts',
optimize: 'none',
optimizeAllPluginResources: true,
preserveLicenseComments: false,
useStrict: true,
wrap: true
}
}
},
....
After grunt 'build' task is completed I see that template.html content is in main.js and there is no generated templates.js file
After adding (also have to set in copy task to copy requirejs-text plugin form app to dir folder ):
stubModules: ['text'],
exclude: ['text!../templates.html'],
files are excluded as expected, but there is still no templates.js file. ( get an error as expected: XMLHttpRequest cannot load file:///...../dist/templates.html. Cross origin requests are only supported for HTTP. it works fine with local HTTP )
My question is: What settings am I missing to generate templates.js file with a requirejs optimizer?
p.s. googled, spent all day, tried more than wrote here.
Thank You in Advance

RequireJS - Performance difference with define vs require

I'm trying to understand if there are any potential downsides to the way I am using requirejs. I am fan of using the commonjs syntax, a typical module will look like:
define(function(require) {
"use strict";
var Backbone = require('backbone');
var Templates = require('templates');
var User = require('accounts/models').User;
...
I then compile my application down to a single JS file. My build config looks like so:
name: 'main',
mainConfigFile: '<%= build_dir %>/<%= main_app %>',
out: '<%= build_dir %>/app.min.js',
optimize: 'none',
include: ['main'],
insertRequire: ['main'],
almond:true,
cjsTranslate: true,
findNestedDependencies: true,
preserveLicenseComments: false
My question is, does using this commonjs format pose any performance or optimisation issues that I would avoid if using a define array instead? As I understand it, the cjsTranslate argument converts it to a define call anyway, but I wasn't sure if there was something I was missing? Is it purely a preference / code readability thing?
For reference, my config file (main.js):
require.config({
paths: {
// Libraries
jquery: '../../vendor/jquery/jquery',
underscore: '../../vendor/underscore/underscore',
backbone: '../../vendor/backbone/backbone',
handlebars: '../../vendor/handlebars.js/dist/handlebars',
modernizr: '../../vendor/modernizr/modernizr',
templates: '../templates'
},
shim: {
"underscore":{
exports: "_"
},
"backbone": {
deps: ["underscore", "jquery", "modernizr", "moment"],
exports: "Backbone"
},
"handlebars": {
exports: "Handlebars"
}
}
});
Is it purely a preference / code readability thing?
Yes absolutely. Once you build, R.js convert Commonjs to plain AMD.
The only performance hit would be when using unbuilded project. But for development it is fast enough (I see no clear difference myself).

RequireJS + Optimizer Include modules defined on the main file

I'm using Optimizer for the first time and I am running in some issues or questions.
I'm trying to optimize a main file and it puts, like I've expected, the jQuery, Backbone and Require modules ( and uses then across the whole navigation). But let's say I have a jQuery Plugin that I use on several views. I've tried to add it in the main file using the "include" option on the build.js file. It adds it ( e.g jQuery Slides ) but as I have a view with define("jquery-slides") ( again, an example ) the browser loads the file of the plugin again. Even if it is on the main built file.
Is this suppose to happen? Can I fix this?
Thanks.
Here is some code. Hope it helps =)
build.js
{
baseUrl: "javascripts/",
appDir: "..",
dir: "dist",
name: "main-site",
include: ['libs/requirejs/require', jquery-slides'],
insertRequire: ['main-site'],
paths: {
"main-site": 'main-site',
'jquery': 'libs/jquery/jquery',
'jquery-slides': 'libs/jquery/plugins/slides.min.jquery'
}
}
main-site.js
require.config({
baseUrl: "/javascripts/",
paths: {
'jquery': 'libs/jquery/jquery',
'underscore': 'libs/underscore/underscore',
'bootstrap': 'libs/bootstrap/bootstrap.min',
'datepicker': 'libs/bootstrap/plugins/bootstrap-datepicker',
'backbone': 'libs/backbone/backbone.max',
'backbone-paginator': 'libs/backbone/plugins/backbone.paginator',
'backbone-validation': 'libs/backbone/plugins/backbone.validation',
'text': 'libs/requirejs/text',
'templates': '/templates/site',
'views': 'views/site',
'jquery-cookie': 'libs/jquery/plugins/jquery.cookie',
'jquery-raty': 'libs/jquery/plugins/jquery.raty.min',
'jquery-slides': 'libs/jquery/plugins/slides.min.jquery'
},
shim: {
'backbone-paginator': ['backbone'],
'bootstrap': ['jquery'],
'datepicker': ['bootstrap'],
'jquery-cookies': ['jquery'],
'jquery-raty': ['jquery'],
'jquery-slides': ['jquery'],
'backbone-validation': ['backbone']
}
});
require([
'app-site'
], function(App) {
$(function(){
App.initialize();
});
});
Instead of using include I recommend you to declare the modules you want to build. In this way requirejs will package the module and all its dependencies in the optimized bundle.
{
baseUrl: "javascripts/",
appDir: "..",
dir: "dist",
paths: {
"main-site": 'main-site',
'jquery': 'libs/jquery/jquery',
'jquery-slides': 'libs/jquery/plugins/slides.min.jquery'
},
modules : [
{
name : 'main-site',
}
]
}
Further considerations:
If you have jquery-slides included as a dependency in any of your modules define(['jquery-slides'], function() {... } you don't need to use the include directive since all the dependencies of that module will be included in the optimized file
See the documentation of the modules property in this link
https://github.com/jrburke/r.js/blob/master/build/example.build.js#L330
Use the property mainConfigFile to avoid duplications https://github.com/jrburke/r.js/blob/master/build/example.build.js#L35
Good luck and I hope this helps you

Ember.js - Handlebars not recognized if required via Grunt (Node.js)

is anybody else using Grunt as build tool for the Ember web application and is experiencing the same behaviour as I do? At this time, I'm using the framework in version RC3 and I can use my build tool without hassle and import all necessary libraries, uglify and compress them and everything works like a charm.
Anyhow, at least since Ember RC5 I'm not able to use Grunt for building my application anymore as Ember would not recognize Handlebars anymore!. It's always complaining that Ember Handlebars requires Handlebars version 1.0.0-rc.4. Include a SCRIPT tag in the HTML HEAD linking to the Handlebars file before you link to Ember. and right afterwards it says Cannot read property 'COMPILER_REVISION' of undefined which leads me to the assumption that Ember is not recognizing the included Handlebars library.
I haven't changed anything in my app.js (the order of the libraries/frameworks is untouched) except the references to the js files (using Ember RC5/6 instead of RC3 and Handlebars RC4 instead of RC3). But it seems that something breaks the initialization of Ember.Handlebars since then...
Do I get something wrong here? Is there a solution out there so that I can continue using Grunt as build tool?
EDIT
Here's my Gruntfile.js:
/*jshint camelcase: false */
/*global module:false */
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
dev: {
buildPath: '.'
},
prod: {
buildPath: '.'
}
},
/*
Task for uglifyng the application javascript file in production environment
*/
uglify: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
},
prod: {
files: [
{
src: '<%= meta.prod.buildPath %>/js/application.js',
dest: '<%= meta.prod.buildPath %>/js/application.min.js'
}
]
}
},
/*
Task for creating css files out of the scss files
*/
compass: {
prod: {
options: {
environment: 'production',
noLineComments: true,
outputStyle: 'expanded',
cssDir: '<%= meta.prod.buildPath %>/css',
fontsDir: '<%= meta.prod.buildPath %>/fonts',
imagesDir: '<%= meta.prod.buildPath %>/images',
javascriptsDir: '<%= meta.prod.buildPath %>/js'
}
},
dev: {
options: {
environment: 'development',
noLineComments: false,
outputStyle: 'expanded',
cssDir: '<%= meta.dev.buildPath %>/css',
fontsDir: '<%= meta.dev.buildPath %>/fonts',
imagesDir: '<%= meta.dev.buildPath %>/images',
javascriptsDir: '<%= meta.dev.buildPath %>/js'
}
}
},
/*
Task to minify all css files in production mode.
All css files will end with '.min.css' instead of
just '.css'.
*/
cssmin: {
minify: {
expand: true,
cwd: '<%= meta.prod.buildPath %>/css/',
src: ['*.css', '!*.min.css'],
dest: '<%= meta.prod.buildPath %>/css/',
ext: '.min.css'
}
},
/*
Clean up the production build path
*/
clean: {
cssd: ['<%= meta.prod.buildPath %>/css/**/*']
},
/*
A simple ordered concatenation strategy.
This will start at app/app.js and begin
adding dependencies in the correct order
writing their string contents into 'application.js'
Additionally it will wrap them in evals
with # sourceURL statements so errors, log
statements and debugging will reference
the source files by line number.
This option is set to false for production.
*/
neuter: {
prod: {
options: {
includeSourceURL: false
},
files: [
{
src: 'app/app.js',
dest: '<%= meta.prod.buildPath %>/js/application.js'
}
]
},
dev: {
options: {
includeSourceURL: true
},
files: [
{
src: 'app/app.js',
dest: '<%= meta.dev.buildPath %>/js/application.js'
}
]
}
},
/*
Watch files for changes.
Changes in dependencies/ember.js or application javascript
will trigger the neuter task.
Changes to any templates will trigger the ember_templates
task (which writes a new compiled file into dependencies/)
and then neuter all the files again.
*/
watch: {
application_code: {
files: ['js/dependencies/ember.js', 'app/**/*.js'],
tasks: ['neuter:dev']
},
compass: {
files: [
'styles/**/*.scss'
],
tasks: ['compass:dev']
}
},
/*
Runs all .html files found in the test/ directory through PhantomJS.
Prints the report in your terminal.
*/
qunit: {
all: ['test/**/*.html']
},
/*
Reads the projects .jshintrc file and applies coding
standards. Doesn't lint the dependencies or test
support files.
*/
jshint: {
all: ['Gruntfile.js', 'app/**/*.js', 'test/**/*.js', '!js/dependencies/*.*', '!test/support/*.*'],
options: {
jshintrc: '.jshintrc'
}
},
/*
Generate the YUI Doc documentation.
*/
yuidoc: {
name: '<%= pkg.name %>',
description: '<%= pkg.description %>',
version: '<%= pkg.version %>',
options: {
paths: '<%= meta.dev.buildPath %>/app/',
outdir: '<%= meta.dev.buildPath %>/yuidocs/'
}
},
/*
Find all the <whatever>_test.js files in the test folder.
These will get loaded via script tags when the task is run.
This gets run as part of the larger 'test' task registered
below.
*/
build_test_runner_file: {
all: ['test/**/*_test.js']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-neuter');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-yuidoc');
/*
A task to build the test runner html file that get place in
/test so it will be picked up by the qunit task. Will
place a single <script> tag into the body for every file passed to
its coniguration above in the grunt.initConfig above.
*/
grunt.registerMultiTask('build_test_runner_file', 'Creates a test runner file.', function () {
var tmpl = grunt.file.read('test/support/runner.html.tmpl');
var renderingContext = {
data: {
files: this.filesSrc.map(function (fileSrc) {
return fileSrc.replace('test/', '');
})
}
};
grunt.file.write('test/runner.html', grunt.template.process(tmpl, renderingContext));
});
/*
A task to run the application's unit tests via the command line.
It will
- convert all the handlebars templates into compile functions
- combine these files + application files in order
- lint the result
- build an html file with a script tag for each test file
- headlessy load this page and print the test runner results
*/
grunt.registerTask('test', ['neuter', 'jshint', 'build_test_runner_file', 'qunit']);
/*
Configures all tasks which will be executed with production setup
*/
grunt.registerTask('prod_tasks', ['clean', 'compass:prod', 'cssmin', 'neuter:prod', 'uglify:prod']);
/*
Setup for the production build. Sets the production build path.
*/
grunt.registerTask('prod', 'Production Build', function () {
grunt.task.run('prod_tasks');
});
/*
Configures all tasks which will be executed with development setup
*/
grunt.registerTask('dev_tasks', ['compass:dev', 'neuter:dev', 'watch']);
/*
Setup for the development build. Sets the development build path.
*/
grunt.registerTask('dev', 'Development Build', function () {
grunt.task.run('dev_tasks');
});
// Default task
grunt.registerTask('default', 'dev');
/*
Configures all tasks which will be executed with doc setup
*/
grunt.registerTask('doc_tasks', ['yuidoc']);
/*
Setup for the YUI doc generation.
*/
grunt.registerTask('doc', 'Generate YuiDoc Documentation for the App', function () {
grunt.task.run('doc_tasks');
});
};
EDIT 2
I took the ember-1.0.0-rc.6.js and handlebars-1.0.0-rc.4.js files from the starter kit at the Ember.js website and tried to run the Grunt tasks on it. Here's what Chrome is telling me:
EDIT 3
Just in case if anybody cares, here's the link to the raised issue over at the Ember.js Github page: https://github.com/emberjs/ember.js/issues/2894
EDIT 4
Finally, the issue was identified to be a Handlebars inconsistency when dealing with global exports, like #Tao reported in his answer. Here's the link to the Issue on GitHub if you want to follow: https://github.com/wycats/handlebars.js/issues/539
It looks like this issue is being addressed in the next version of Handlebars: https://github.com/wycats/handlebars.js/issues/539 Stay tuned.
You have a mismatch in the version used to compile the Handlebars templates and the version included via the script tag.
If you are using grunt-contrib-handlebars, it uses the npm module handlebars to compile the the templates. The handlebars module/project is independent of Ember and has its own revisions that may or not be compatible with Ember.
To maintain compatibility with Handlebars Ember needs specific versions of handlebars which it is warning you about.
The tricky part here is you need to ensure that grunt-contrib-handlebars is forced to use that specific version of handlebars.
Solution 1: Use shrinkwrap to change grunt-contrib-handlebars's handlebars dependency version.
Solution 2: This is what I am currently using. I have switched to Emblem. The emblem grunt task asks for your handlebars file explicitly so you don't have to drop down to node sub dependency management. And your build includes the same file into your script tags, thus avoiding duplication/mismatch for future revisions.
Edit: After Gruntfile edit
Looking at the Gruntfile I don't see anything amiss. Looks like a standard build process, js -> neuter -> (if prod) -> uglify etc.
I think you need to try refreshing both emberjs and handlebars js files. Try using the files from the starter kit itself, those definitely work together.
And verify this for your index.html by looking at the unminified source in Chrome/Inspector. Handlebars has the revision numbers below the banner something like Handlebars.VERSION and Handlebars.COMPILER_REVISION. Match those with what you see in the ember.js file, somewhere below #submodule ember-handlebars-compiler in the Ember.assert.

Resources