5

我有一个问题,我似乎无法找到答案。我目前正在构建一个消费库,我想使用 requirejs 使其更加模块化。我有以下项目结构......

- example
    - scripts
        - otter
            - libs
                - signals
                    signals.js
            - modules
                subModule1.js
                subModule2.js
            otter.js
    index.htm

- src
    - libs (copied to example folder at build time)
        - signals
            signals.js
    - modules
        subModule1.coffee
        subModule2.coffee
    - otter.coffee

我想要做的是能够从我的任何其他文件中获取signals.js文件和我的任何模块,而无需在require中设置路径,或者我不必知道项目是如何设置的在开发时。

例如,我试图在我的 otter.coffee 文件中做的是:

define ['/libs/signals/signals'], (signals) ->
    # I've also tried './libs/signals/signals' and 'libs/signals/signals'

这似乎不起作用,因为 require 找不到 signals.js 文件。

如何让 requirejs 加载相对于当前文件的模块?我读过我可以要求 require 作为依赖项,并且该 require 的路径将设置为文件的路径,但这似乎也不起作用。它会引发一个尚未加载的错误,即:e -

define (require) ->
    signals = require './libs/signals/signals'

有什么想法可以做到这一点吗?我需要改变图书馆的结构吗?我必须强制一个特定的结构吗?我是否要求那些使用它的人在他们的需求配置中包含某些路径?

提前谢谢了!

编辑-

我注意到,如果我在 main.js 文件中为我的库命名为 require,则信号的 require(通过 require 或 define)不起作用(一直找不到 404)。但是,如果我不给我的图书馆起别名,一切都很好..

例如,如果我的 require main.js 文件有..

...
paths: {
    'otter': 'scripts/otter/otter'
}
...

then the require of signals fails. However, if I don't have the path and I require otter through it's direct path, the require of signal works. I'm requiring signal like this in otter.js ...

define (require) ->
    signals = require './libs/signals/signals'

It this a bug with require.js?

4

1 回答 1

2

RequireJS uses two functions to do its job: define() and require().

My understanding is that define() lists dependencies and only loads modules; loading dependencies that are not modules (those who not use define()) is done with require().

Because only modules can load modules, there have to be someone else to load the first module. In your case, to use signals.js in otter.js the first has to be a module and the second has to use require(). I guess that a require() is always needed before any define() uses.

otter.js:

require.config({
  paths: {
    'signals': 'libs/signals/signals',
    'module1': 'modules/subModule1'
  }
});

require(['signals'], function(signals) {
  signals.initialize();
});

signals.js:

define(['module1'], function(module) {
  return {
    initialize: function() {
      module.doStuff();
    }
  }
});

subModule1.js:

define([], function() {
  return {
    doStuff: function() {
      console.log('hello world');
    }
  }
});

ps. Loading modules relative to the current file do not seems to be allowed: a baseUrl property is used to configure every modules paths in requirejs.config().

于 2012-07-11T15:33:25.627 回答