javascript 从 Firebug/Chrome 控制台与 require.js 模块交互?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8458561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:30:45  来源:igfitidea点击:

Interacting with require.js modules from the Firebug/Chrome console?

javascriptfirebuggoogle-chrome-devtoolsrequirejs

提问by erikcw

I'm just getting started with require.js. I have successfully wrapped jquery, some plugins, and a couple of my own modules. I'm trying to interact with my modules (or jquery) from Firebug (or Google Chrome's JS console), and I'm not having much luck.

我刚刚开始使用 require.js。我已经成功地封装了 jquery、一些插件和几个我自己的模块。我正在尝试从 Firebug(或 Google Chrome 的 JS 控制台)与我的模块(或 jquery)交互,但我运气不佳。

What is the correct way to access these modules from the console?

从控制台访问这些模块的正确方法是什么?

回答by benastan

Say we have module /app/scripts/methodsModule.js that returns a few methods:

假设我们有模块 /app/scripts/methodsModule.js 返回一些方法:

define({
    someMethod: function() {
        // do stuff
    },
    anotherMethod: function() {
        // do some more stuff
    }
});

In our data-main file /app/scripts/main.js we have:

在我们的数据主文件 /app/scripts/main.js 中,我们有:

require(['methodsModule'], function(methods) {
    methods.someMethod() // call someMethod
    methods.anotherMethod() // call anotherMethod
})

Once requireJS loads up our data-main, we can access any modules that have already been loaded by requireJS from the javascript console command line like so:

一旦 requireJS 加载了我们的 data-main,我们就可以从 javascript 控制台命令行访问任何已经被 requireJS 加载的模块,如下所示:

>> methods = require('methodsModule'); // requireJS has module methodsModule stored
>> methods.someMethod() // call someMethod
>> methods.anotherMethod() // call anotherMethod

If a module hasn't been loaded by a call to require() or define(), we have to pass our own callback for the require function to call after the module has been loaded:

如果模块没有通过调用 require() 或 define() 加载,我们必须传递我们自己的回调,以便在加载模块后调用 require 函数:

>> myCB = function(methods) { methods.someMethod() }
>> require(['methodsModule'], myCB)

Otherwise, requireJS throws an error saying that the module has not yet been loaded..

否则,requireJS 会抛出一个错误,指出模块尚未加载。

回答by Valentin Nemcev

There is a way without using callbacks.

有一种不使用回调的方法。

If you module was not required in console or you application before, you can just require it first:

如果您之前在控制台或应用程序中不需要您的模块,您可以先要求它:

require(['methodsModule']);

after that you can use "dynamic" require to access it:

之后,您可以使用“动态”要求访问它:

require('methodsModule').someMethod();