Requirejs:当我尝试通过requirejs获取它时,函数未定义

问题描述 投票:0回答:1

我尝试从js文件中获取一些函数,我通过requirejs包含它,但它不起作用。

这是我做的:

test.js

define(['jquery'], function($){
   "use strict";
       function hello()
        {
            alert('hello from function');
        }    
});

requirejs-config.js

var config = {
    map: {
        '*': {
            module: 'Vendor_module/js/test',
        }
    }
};
console.log('foo'); // i get well "foo" in console

HTML

<script type="text/javascript">
    require(['jquery', 'module'], function($) {
        hello();
    });
</script>

结果:

ReferenceError: hello is not defined

谢谢。

javascript jquery requirejs
1个回答
0
投票

你需要在test.js中返回hello函数

define(['jquery'], function($){

"use strict";
      return function hello()
        {
            alert('hello from function');
        }    
});

并且您可以在要求的回调中使用该函数。

require(['jquery', 'module'], function($, hello) {
    hello();
});
© www.soinside.com 2019 - 2024. All rights reserved.