如何在其他文件中调用 RequireJS 函数?如何分离 RequireJS 文件

How to call RequireJS functions in other files? How to separate RequireJS files?

本文关键字:RequireJS 文件 何分离 分离 调用 其他 函数      更新时间:2023-09-26

而不是拥有一大堆"定义"的巨型js文件,我如何从其他文件中调用我的各种"定义"函数?

我一直在复制这些示例,但仍然无法使其工作:

  • 示例-多页
  • 示例-多页填充程序
  • example-jquery-shim

这是我到目前为止所拥有的:

主.js

require.config({
    baseUrl: '',
    paths: {
       jquery: '../libraries/jquery-1.10.2.min',
       simControlView: '../javascripts/simControlView'
    }
});
require(['jquery','loadPage'], function( $,loadPage) 
{ 
        loadPage();
});
define('loadPage', ['jquery'], function($)
{
    var simControlView = require(['./simControlView']);
    return function()
    {
         simControlView.showSimControlView(); //having problem here
    };
});

simControlView.js

define(['jquery'], function ($) {
    return {
        showSimControlView: function () {
            console.log("Hi!!");
        }
    }
});

这是我收到的错误:

Uncatch TypeError: Object function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(H(c))return v(A("requireargs", "Invalid require call"),h);if(a&&s(N,e))return Ne;if(j.get)return j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module 尚未为上下文加载名称"+g+":"+b+(a?":"。用 require([])")):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return d} 没有方法 'showSimControlView'

看到我做错了什么吗?任何帮助不胜感激!

尝试将所有依赖项移动到传递给 define() 的依赖项列表中。

此外,排序可能很重要。 即模块的define()可能需要在需要它的require()之前(谈论'loadPage'模块)。

另外,如果你的paths配置调用模块'simControlView',那么它需要被称为'simControlView',而不是'./simControlView'

例如:

define('loadPage', ['jquery', 'simControlView'], function($, simControlView) {
    return function() {
         simControlView.showSimControlView();
    };
});
require(['jquery', 'loadPage'], function($, loadPage) {
    loadPage();
});