Requirement require.js requires

I am trying to use requireJS, but I want to build a hierarchy of dependencies: main requires obr.platcom and obr.platcom requires obr (for example).

I have this file hierarchy:

 - index.html -> js - main.js -> lib - jquery.js - require.js -> obr [my own 'libraries'] - obr.js - obr.platcom.js 

index.html

 <!DOCTYPE html> <html lang="es"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <title>Platcom</title> <script type="text/javascript" src="js/lib/jquery.js"></script> <script data-main="js/main" src="js/lib/require.js"></script> </head> <body> </body> </html> 

main.js

 $(document).ready(function() { require(["obr/obr.platcom"], function() { obr.hola(); var myPlatcom = obr.platcom(); myPlatcom.test(); }); }); 

obr.js

 var obr = {}; obr.hola = function() { alert('Hola OBR'); }; 

obr.platcom.js

 require(["obr.js"],function() { obr.platcom = function(params) { var that = {}; var test = function test() { alert('Hola Platcom!'); } that.test = test; return that; } }); 

If I need the obr and obr.platcom in main , everything works, but if I use this nested style, I get the following error:

 Uncaught ReferenceError: obr is not defined main.js:3 

Do you know what I am doing wrong? Thank you in advance.

+4
source share
1 answer

Ok, you made some mistakes.

  • You need to specify the dependency that you enter as an argument. For example, require(["obr/obr.platcom"], function() { will not do much unless you specify how to call the required module. You need this:

     require(["obr/obr.platcom"], function( obr ) { 

    That way, you know which variable your required object is in.

  • The obr.js variables are in the global scope. You need to wrap them with a call to the require or define function. The following would be done:

     define(function() { var obr = {}; obr.hola = function() {}; return obr; }); 

    You may have noticed some things that do not match your latest file.

  • If you want your module to be imported somewhere, you must define it. Therefore, you should use the define function, not require . The define function should return an object. Here is the obr.platcom.js fixed file:

     // If you don't use "define" for the obr.js file too, this won't work define(['obr'], function( obr ) { obr.platcom = function() {}; // Don't forget to return the obr object, or the require of // the main file won't return anything return obr; }); 

Thus, everything is done correctly. Or at least the require.js way wants you to do something.

Hopefully this will show you how require.js can be used effectively to simply split your code into modules :)

+7
source

Source: https://habr.com/ru/post/1413932/


All Articles