gpt4 book ai didi

javascript - require 的同步形式在解决循环依赖时会抛出错误,除非我重命名 require

转载 作者:行者123 更新时间:2023-11-28 08:18:42 28 4
gpt4 key购买 nike

我在 require 中有一个奇怪的行为,我不知道如何避免(或者也许我的基础知识错误?)。

考虑以下代码:

define (require) ->

potoo = require "potoo"
service = require "communication.data"

downloadIfNeeded = ->
# ...
service.download()

new potoo.App
pageContainer: potoo.UI.NGStylePage
userRequired: true
stdRoute: "overview"
onLogin: downloadIfNeeded

这是行不通的,因为“communication.data”本身需要“app”(显示的代码)。所以我们显然有一个循环依赖。失败并显示“未捕获错误:尚未为上下文加载模块名称“app”:_”

由于 downloadIfNeeded 函数只有在用户实际单击某些内容后才会被调用,因此我认为类似以下内容应该有效:

define (require) ->

potoo = require "potoo"

downloadIfNeeded = ->
service = require "communication.data"
service.download()

...

但这实际上会引发与上面相同的错误。为了让它工作,我必须使用一些技巧。我用其他名称为 require 函数别名:

define (require) ->

potoo = require "potoo"
reqs = require

downloadIfNeeded = ->
service = reqs "communication.data"
service.download()

...

这是最好的方法吗?或者您会推荐 requirejs 也支持的 CommonJS 样式 (module.export)。

最佳答案

我在这里做了测试并找到了解决方案。你所拥有的相当于这个 JavaScript:

define(function (require) {

这足以能够使用 require 的(假)同步形式。但是,当您尝试使用同步 require 并且存在循环依赖项时,RequireJS 会给您带来错误。你需要的是这样的:

define(function (require, exports, module) {

这样您的模块就可以使用 exports 导出其值,因此 RequireJS 拥有一个可以在模块完成初始化时更新的对象。

关于javascript - require 的同步形式在解决循环依赖时会抛出错误,除非我重命名 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23271218/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com