I have pretty rudimentary knowledge in javascript. I plan on implementing RequireJS in my application for dynamic script loading & dependency management. Going through an example
In the example there are 4 js files purchase.js, products.js, credits.js. main.js.
main.js initializes the flow. I understand main.js needs the require
method.
require(["purchase"],function(purchase){
purchase.purchaseProduct();
});
but then the every js files begins with define()
for an instance a code snippet from purchase.js
define(["credits","products"], function(credits,products) {
console.log("Function : purchaseProduct");
return {
purchaseProduct: function() {
Now as per this example say if I have n
js files in my project & I write the code in this fashion. In future say I need to remove RequireJS from my application. I have to edit n
js files.
Isn't this too much tight coupling of js code with requirejs library? Unlike the standard way of including js files using the script
tag in html files.
Had I included the scripts with the script tag in the html file. I don't have to edit all the js files for any change.
Is there any other way to declare the dependencies for every js file of the project in a centralized place?
What you show in your question does not indicate tight coupling with RequireJS. You are using the AMD spec to declare your modules and loading them. The only thing this entails is that you need to have a module loader which is compatible with AMD. This could be RequireJS, or it could be Almond or it could be Node.js with the node-amd-loader package. And I believe there are even more options available.
If you do not want the
define
calls to appear in each of your files, and still preserve the modularity of your code, and have the dependencies all located in a "centralized place", RequireJS does not have built-in support for this. You might be able to hijack theshim
configuration option for this purpose but I don't see this being a simple matter. Theshim
setting is pretty much a crutch that allows using non-modular code with RequireJS and it relies on symbols being available on the global space, this goes against the goal of preserving modularity. Otherwise, you could design a build process that would read a file and on the basis of this file build each source file into a proper AMD module by wrapping the code into adefine
call.