I am having an issue with an undefined variable in my module set up, best to explain by example, I have:
common.js (config for requirejs)
require([
'module/polyfills/someModule'
], function(
module
) {
module.init();
});
module/polyfills/someModule.js
define([
'underscore',
'config',
'text!tpl/utils/textTemplate.html'
], function(_, config, template) {
// ref 1
return {
init: function() {
// ref 2
// do stuff
},
events: function() {
// add some events
},
};
});
If I put a breakpoint at the comment ref 1 I can see the config variable and its properties. However if I put a breakpoint at ref 2 then config is undefined. However underscore and the template are not undefined.
I have removed anything special about config in my require configuration. Config looks like this:
config.js
define([], function (clickType) {
return {
clickType: 'test'
};
});
There are no errors in console and I am very certain this is not a circular dependency!
the comment place at ref2 is a closure where you haven't accessed config. The function is created at parse and it is a closure, whatever you access inside it is available. simple test, add the following line of code at //ref2
var myConfig = config;
Now you will see config as defined.
I am trying to use gulp-requirejs to build a demo project. I expect result to be a single file with all js dependencies and template included. Here is my gulpfile.js
var gulp = require('gulp');
var rjs = require('gulp-requirejs');
var paths = {
scripts: ['app/**/*.js'],
images: 'app/img/**/*'
};
gulp.task('requirejsBuild', function() {
rjs({
name: 'main',
baseUrl: './app',
out: 'result.js'
})
.pipe(gulp.dest('app/dist'));
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['requirejsBuild']);
The above build file works with no error, but the result.js only contains the content of main.js and config.js. All the view files, jquery, underscore, backbone is not included.
How can I configure gulp-requirejs to put every js template into one js file?
If it is not the right way to go, can you please suggest other method?
Edit
config.js
require.config({
paths: {
"almond": "/bower_components/almond/almond",
"underscore": "/bower_components/lodash/dist/lodash.underscore",
"jquery": "/bower_components/jquery/dist/jquery",
"backbone": "/bower_components/backbone/backbone",
"text":"/bower_components/requirejs-text/text",
"book": "./model-book"
}
});
main.js
// Break out the application running from the configuration definition to
// assist with testing.
require(["config"], function() {
// Kick off the application.
require(["app", "router"], function(app, Router) {
// Define your master router on the application namespace and trigger all
// navigation from this instance.
app.router = new Router();
// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default. Change in app.js.
Backbone.history.start({ pushState: false, root: '/' });
});
});
The output is just a combination this two files, which is not what I expected.
gulp-requirejs has been blacklisted by the gulp folks. They see the RequireJS optimizer as its own build system, incompatible with gulp. I don't know much about that, but I did find an alternative in amd-optimize that worked for me.
npm install amd-optimize --save-dev
Then in your gulpfile:
var amdOptimize = require('amd-optimize');
var concat = require('gulp-concat');
gulp.task('bundle', function ()
{
return gulp.src('**/*.js')
.pipe(amdOptimize('main'))
.pipe(concat('main-bundle.js'))
.pipe(gulp.dest('dist'));
});
The output of amdOptimize is a stream which contains the dependencies of the primary module (main in the above example) in an order that resolves correctly when loaded. These files are then concatenated together via concat into a single file main-bundle.js before being written into the dist folder.
You could also minify this file and perform other transformations as needed.
As an aside, in my case I was compiling TypeScript into AMD modules for bundling. Thinking this through further I realized that when bundling everything I don't need the asynchronous loading provided by AMD/RequireJS. I am going to experiment with having TypeScript compile CommonJS modules instead, then bundling them using webpack or browserify, both of which seem to have good support within gulp.
UPDATE
My previous answer always reported taskReady even if requirejs reported an error. I reconsidered this approach and added error logging. Also I try to fail the build completely as described here gulp-jshint: How to fail the build? because a silent fail really eats your time.
See updated code below.
Drew's comment about blacklist was very helpfull and gulp folks suggest using requirejs directly. So I post my direct requirejs solution:
var DIST = './dist';
var requirejs = require('requirejs');
var requirejsConfig = require('./requireConfig.js').RJSConfig;
gulp.task('requirejs', function (taskReady) {
requirejsConfig.name = 'index';
requirejsConfig.out = DIST + 'app.js';
requirejsConfig.optimize = 'uglify';
requirejs.optimize(requirejsConfig, function () {
taskReady();
}, function (error) {
console.error('requirejs task failed', JSON.stringify(error))
process.exit(1);
});
});
The file at ./dist/app.js is built and uglified. And this way gulp will know when require has finished building. So the task can be used as a dependency.
My solution works like this:
./client/js/main.js:
require.config({
paths: {
jquery: "../vendor/jquery/dist/jquery",
...
},
shim: {
...
}
});
define(["jquery"], function($) {
console.log($);
});
./gulpfile.js:
var gulp = require('gulp'),
....
amdOptimize = require("amd-optimize"),
concat = require('gulp-concat'),
...
gulp.task('scripts', function(cb) {
var js = gulp.src(path.scripts + '.js')
.pipe(cached('scripts'))
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(remember('scripts'))
.pipe(amdOptimize("main",
{
name: "main",
configFile: "./client/js/main.js",
baseUrl: './client/js'
}
))
.pipe(concat('main.js'));
.pipe(gulp.dest(path.destScripts));
}
...
This part was important:
configFile: "./client/js/main.js",
baseUrl: './client/js'
This allowed me to keep my configuration in one place. Otherwise I was having to duplicate my paths and shims into gulpfile.js.
This works for me. I seems that one ought to add in uglification etc via gulp if desired. .pipe(uglify()) ...
Currently I have to duplicate the config in main.js to run asynchronously.
....
var amdOptimize = require("amd-optimize");
...
var js = gulp.src(path.scripts + '.js')
.pipe(cached('scripts'))
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(remember('scripts'))
.pipe(amdOptimize("main",
{
name: "main",
paths: {
jquery: "client/vendor/jquery/dist/jquery",
jqueryColor: "client/vendor/jquery-color/jquery.color",
bootstrap: "client/vendor/bootstrap/dist/js/bootstrap",
underscore: "client/vendor/underscore-amd/underscore"
},
shim: {
jqueryColor : {
deps: ["jquery"]
},
bootstrap: {
deps: ["jquery"]
},
app: {
deps: ["bootstrap", "jqueryColor", "jquery"]
}
}
}
))
.pipe(concat('main.js'));
Try this code in your gulpfile:
// Node modules
var
fs = require('fs'),
vm = require('vm'),
merge = require('deeply');
// Gulp and plugins
var
gulp = require('gulp'),
gulprjs= require('gulp-requirejs-bundler');
// Config
var
requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('app/config.js') + '; require;'),
requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
name: 'main',
baseUrl: './app',
out: 'result.js',
paths: {
requireLib: 'bower_modules/requirejs/require'
},
insertRequire: ['main'],
// aliases from config.js - libs will be included to result.js
include: [
'requireLib',
"almond",
"underscore",
"jquery",
"backbone",
"text",
"book"
]
});
gulp.task('requirejsBuild', ['component-scripts', 'external-scripts'], function (cb) {
return gulprjs(requireJsOptimizerConfig)
.pipe(gulp.dest('app/dist'));
});
Sorry for my english. This solution works for me. (I used gulp-requirejs at my job)
I think you've forgotten to set mainConfigFile in your gulpfile.js. So, this code will be work
gulp.task('requirejsBuild', function() {
rjs({
name: 'main',
mainConfigFile: 'path_to_config/config.js',
baseUrl: './app',
out: 'result.js'
})
.pipe(gulp.dest('app/dist'));
});
In addition, I think when you run that task in gulp, require can not find its config file and
This is not gulp-requirejs fault.
The reason why only main.js and config.js is in the output is because you're not requiring/defining any other files. Without doing so, the require optimizer wont understand which files to add, the paths in your config-file isn't a way to require them!
For example you could load a main.js file from your config file and in main define all your files (not optimal but just a an example).
In the bottom of your config-file:
// Load the main app module to start the app
requirejs(["main"]);
The main.js-file: (just adding jquery to show the technique.
define(["jquery"], function($) {});
I might also recommend gulp-requirejs-optimize instead, mainly because it adds the minification/obfuscation functions gulp-requirejs lacks: https://github.com/jlouns/gulp-requirejs-optimize
How to implement it:
var requirejsOptimize = require('gulp-requirejs-optimize');
gulp.task('requirejsoptimize', function () {
return gulp.src('src/js/require.config.js')
.pipe(requirejsOptimize(function(file) {
return {
baseUrl: "src/js",
mainConfigFile: 'src/js/require.config.js',
paths: {
requireLib: "vendor/require/require"
},
include: "requireLib",
name: "require.config",
out: "dist/js/bundle2.js"
};
})).pipe(gulp.dest(''));
});
In my web site, I have bunch of JavaScript files, all for different use but the login page only needs the jquery and loginValidate files. When I attach my main.js, it is suppose to load only these two files by checking the conditions. How to do that?
My config file:
requirejs.config({
baseUrl:"scripts",
paths:{
//libraries
jquery :"lib/jquery-1.9.0.min",
jqueryUI :"lib/jquery-ui-1.9.2.custom.min",
underScore :"lib/underscore-min",
backBone :"lib/backbone-min",
//scripts
appInit :"js/tasklist",
loginValidate :"js/loginValidate"
},
shim:{
"underScore":{
exports: "_"
},
"backBone":{
exports:"Backbone",
deps:["underScore"]
},
"appInit" : {
deps:["jquery","jqueryUI","underScore","backBone"]
},
"jqueryUI":{
deps:["jquery"]
},
"loginValidate":{
deps:['jquery']
}
}
});
It is only needed on login page:
require(["jquery","loginValidate"], function($,validate){
how can i call the loginValidate function?
});
The loginValidate function:
define(function(){
var tasklistHandler = function (params) {
//params take care.. to validate
};
$(function(){ // calling internally the function
var paramsLoginForm = {
loginForm : $('#tlLoginForm')
}
tasklistHandler(paramsLoginForm);
});
})
Is this the correct way to do? I am using also Backbone.js to utilise some other page; how can I proceed for those pages?
The problem you have is the lack of "return" in the "factory" function (the callback function you pass to the define call in the last snippet).
Instead you need to have something like this there:
define(function(){
return function (params) {
//params take care.. to validate
};
})
And in your require call you use run the function that is returned to you by factory function:
require(["jquery","loginValidate"], function($, validate){
var paramsLoginForm = {
loginForm : $('#tlLoginForm')
}
// \|/ that is what is returned by `define`'s callback function.
validate(paramsLoginForm);
});
I'm having trouble getting a route to match using crossroads with requirejs. Well, it probably has nothing to do with requirejs, just thought I'd mention it.
This is what my code looks like:
require.config({
shim: {
/* use shims to define dependencies for modules. e.g.,
'jquery.colorize': ['jquery'],
'jquery.scroll': ['jquery'],
*/
'crossroads': ['signals', 'can']
},
paths: {
"jquery": "http://code.jquery.com/jquery-1.8.2",
"can": "/scripts/can/amd/can",
"can.fixture": "/scripts/can/amd/can/util/fixture",
"signals": "/scripts/signals/signals",
"crossroads": "/scripts/crossroads/crossroads"
}
});
require(['jquery', 'crossroads', 'controllers/project'], function ($, crossroads, projectController) {
var projectRoute = crossroads.addRoute('projects', function () {
$(document).ready(function () {
console.log('projects ready');
$.when(ProjectModel.findAll()).then(function (projectResponse) {
var projects = new SortList(projectResponse);
console.log('doc ready projects=', projects);
new ProjectsControl('#projects', {
projects: projects,
defaultSort: 'priority'
});
});
});
})
console.log('matched: ', projectRoute.match(window.location.href));
});
The url that it's trying to match is http://localhost:34382/projects and the output of console.log is "matched: false"
Any suggestions?
I figured out that I need to change what I'm matching on. I've changed this line
console.log('matched: ', projectRoute.match(window.location.href));
to this
console.log('matched: ', projectRoute.match(window.location.pathname + window.location.search));
and now it works.
Also realized that you have to explicitly call crossroads.parse() somewhere for it to work (or am I missing something?)
so at the end of my require function I call this and my route is found
crossroads.parse(window.location.pathname + window.location.search);
Also, in case anyone is wondering, I'm using CanJS as the client-side MVC framework and ASP.NET MVC4 as the server-side.
I'm pretty new to require.js and having problems loading i18next.js.
main.js
require(["lib/jquery", "lib/i18next", "config.i18next", "constants"],
function(util) {
console.log("loaded javascript files");
});
and config.i18next.js
var option = {resGetPath: '../translations/__lng__.json' };
i18n.init(option, function(t) {
console.log("Language initialization successfull");
});
I always get the error
Uncaught ReferenceError: i18n is not defined config.i18next.js:2
I know who to use i18next, and everything works fine when loading the javascript files traditionally.
EDIT:
Meanwhile I got it working with shim like this:
requirejs.config({
shim: {
'lib/i18next' : ['lib/jquery'],
}
});
require(["lib/i18next"], function(i18n) {
var options = {
resGetPath: 'translations/__lng__.json',
preload: ['de', 'en']
};
i18n.init(options, function(t) {
});
});
and I can translate in other files with $.t("key"); , but when now I can't change the language programatically with i18n.setLng() because the variable can't be found ReferenceError: Can't find variable: i18n.
--- i18next comes now with amd build ---
this should solve all issues using i18next with amd. you can grab it at http://i18next.com