user1841488
user1841488

Reputation: 5

requirejs define a module can not get the return value

I can not get the exports value When I import external links js file (main.js) as a dependency with requirejs,see the code.

console.log(m) //undefined

but I define the module "t" as a dependency in internal,it can get the return value,see the code.

console.log(n) //test

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>

    <script src="https://cdn.bootcss.com/require.js/2.3.3/require.min.js" ></script>

	<script type="text/javascript">
            define("t",["main"],function(m){
            	console.log(m) //undefined
            	
            	return "test";
            	
            });
            require(["t"],function(n){
            	console.log(n) //test
            	
            });
        </script>
</body>
</html>

Here is the main.js:

define("m",[],function(){

    return "test";
})

So what's the wrong with it?

Upvotes: 0

Views: 562

Answers (1)

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

Define your main.js module like this and it should work fine:

define([],function(){

    return "test";
});

Your HTML will be:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>

  <script src="https://cdn.bootcss.com/require.js/2.3.3/require.min.js"></script>

  <script type="text/javascript">
    requirejs.config({
      baseUrl: '/', // set proper base path


      paths: {

        "main": "...path to main js...."

      }


    });

    define("t", ["main"], function(m) {
      console.log(m) 

      return "test";

    });

    require(["t"], function(n) {
      console.log(n) //test

    });
  </script>
</body>

</html>

Here is a working pen

Upvotes: 0

Related Questions