简体   繁体   中英

RequireJs - Nested require JS File

I have 4 script file.

  1. script.js -> main script file
  2. testApp.js
  3. addition.js
  4. multiplication.js

script.js requires testApp.js and testApp.js require addition.js and multiplication.js.
I need the output of calculate function which is in script.js

Error - add() is not defined.

My Code -

Script.js

require(["testApp"],function(){
    alert("hello Script");
    alert(calculate());
});

testApp.js

define(["addition","multiplication"], function calculate(){ 
    alert("hello testApp");
    var c;
    var a=5;
    var b=10;
    c = add(a,b)+mul(a,b);
    return c;
});

addition.js

define(function add(a,b){
    alert("hello Addition");
    return a+b;
});

multiplication.js

define(function mul(a,b){
    alert("hello Multiplication");
    return a*b;
});

I tried this way in local and it works:

testApp.js

define(["addition","multiplication"], function(addition, multiplication){ 
  alert("in testApp");
  return {
    calculate :function(){
        alert("hello testApp");
        var c;
        var a=5;
        var b=10;
        return addition.add(a,b)+ multiplication.mul(a,b);
     }
 } 
});

addition.js

 define([], function(){
    return {
     add: function(a,b){
      alert("hello Addition");
      return a+b;
     }
   }
});

multiplication.js

 define([], function(){
    return {
     mul: function(a,b){
      alert("hello Multiplication");
      return a*b;
     }
   }
});

and finally in your code:

   require(["testApp"],function(testApp){
     alert("hello main script");
     alert(testApp.calculate());
   });

Try like this

addition.js

function add(a,b){
    alert("hello Addition");
    return a+b;
}

multiplication.js

function mul(a,b){
    alert("hello Multiplication");
    return a*b;
}

testApp.js

function calculate(){ 
    alert("hello testApp");
    var c;
    var a=5;
    var b=10;
    c = add(a,b)+mul(a,b);
    return c;
}

and finally Script.js

requirejs.config({
    shim: {
        'testApp': ['addition','multiplication'],
    }
});
require(["testApp"], function () {
    alert("hello Script");
    alert(calculate());
});

define the dependency using shim in requireJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM