With the scope of having the javascript side of an existing app, better structured, easy to manage/understand and better management of scripts that need to run for different parts of the site, I decided to try and implement RequireJS as a solution.
I also use grunt, and I took advantage of the grunt-contrib-requirejs existing module, to manage it all in one place.
Grunt
requirejs: {
options: {
baseUrl: "./",
mainConfigFile: "<%= project.scripts %>/build.js",
name: "<%= project.bowerDir %>/almond/almond",
out: "<%= project.scripts %>/main.min.js"
},
debug: {
options: {
optimize: 'none'
}
},
production: {
options: {
optimize: 'uglify2'
}
}
},
build.js
requirejs.config({
baseUrl: "/",
// automatically require on page load in debug mode
deps: ['assets/scripts/main'],
//deps: ['main'],
// automatically require this for production build
// insertRequire: ['assets/scripts/main'],
paths: {
"bower" : "../../../bower_components",
"module": "../modules",
"jquery" : "bower_components/jquery/dist/jquery",
"jquery.ui" : "assets/scripts/vendor/jquery-ui-1.10.3.custom.min",
"jquery.ui.touch-punch": "assets/scripts/vendor/jquery.ui.touch-punch.min",
"lazyload" : "bower_components/jquery.lazyload/jquery.lazyload",
"swfobject" : "assets/scripts/vendor/swfobject",
"cookie" : "assets/scripts/vendor/jquery.cookie",
"query" : "assets/scripts/vendor/jquery.query",
}
}).call(this);
// Load the main app module to start the app
// requirejs(["app", "module/home"]);
main.js
define([
'jquery', 'jquery.ui', 'jquery.ui.touch-punch',
'lazyload', 'swfobject', 'cookie', 'query'
], function (require) {
'use strict';
$(function () {
alert('main.');
// ....
});
});
So, I got to the point where I invoke my build.js (development env... read this article: Grunt.js and Require.js - compiling with r.js)...
<script data-main="/assets/scripts/build" src="/assets/scripts/vendor/require.js"></script>
So, the build.js is loaded, and then the main.js also, and the alert executes. So far, so good... now comes the doubts:
- I can't seem to understand how to work with dependencies (from
jquerytocookieandquery). How can I expect them to be already loaded? Because, on mymain.jsI will invoke those libraries, but I get errors due to the fact that they're not loaded. - Let's say for
/articlesI havearticles.js, for/profilesI haveprofiles.js. How will I manage to process each.jsaccording to the pages I need/want to?main.jsis the common file, but there are separate.jsfiles for each module in the web. - Am I missing something?
$ = require('jquery')would be how you assign jQuery to the dollar sign so long as it's loaded via NPM in your node_modules. Want to use libs already written?module.exportswhat you're returning. It makes web components awesome. I haven't used RequireJS since I've found it.