配置时使用RequireJS配置模块取决于RequireJS

gre*_*ech 7 javascript node.js requirejs

如果我在文档中遗漏了这一点,请道歉.基本上我想使用RequireJS模块配置功能.我想集中管理包中模块的配置值.

这是文档中的一个示例:

requirejs.config({
    config: {
        'bar': {
            size: 'large'
        },
        'baz': {
            color: 'blue'
        }
    }
});

//bar.js, which uses simplified CJS wrapping:
define(function (require, exports, module) {
    //Will be the value 'large'
    var size = module.config().size;
});

//baz.js which uses a dependency array,
define(['module'], function (module) {
    //Will be the value 'blue'
    var color = module.config().color;
});
Run Code Online (Sandbox Code Playgroud)

我的问题是我的配置信息会更复杂,并且本身会有依赖关系.我想要做:

requirejs.config({
    config: {
        'bar': {
            path: path.dirname(module.uri)
            key: crypto.randomBytes(64)
        },
    }
});
Run Code Online (Sandbox Code Playgroud)

我的配置中的变量需要使用requireJS来评估.

对我来说,在RequireJS配置(加载模块所需的配置)和用户模块配置之间存在逻辑分离是有意义的.但我目前正在努力找到这个:(

jrb*_*rke 6

对于这种解决方案,我希望模块依赖于"config"模块,您可以使用路径配置交换另一个模块.因此,如果"bar"需要一些配置,"bar.js"将如下所示:

define(['barConfig'], function (config) {
});
Run Code Online (Sandbox Code Playgroud)

然后barConfig.js可能有你的其他依赖项:

define(['crypto'], function (crypto) {
    return {
      key: crypto.randomBytes(64)
    }
});
Run Code Online (Sandbox Code Playgroud)

然后,如果您需要不同的配置,例如,生产与开发,请使用paths config将barConfig映射到其他值:

requirejs.config({
  paths: {
    barConfig: 'barConfig-prod'
  }
});
Run Code Online (Sandbox Code Playgroud)


gre*_*ech 0

经过更多思考后,我想出了一个解决方法。它不是特别漂亮,但似乎确实有效。

我只需执行两次 requireJS(...) ,第一次创建配置,第二次使用配置加载应用程序模块。

requireJSConfig = 
    baseUrl: __dirname
    nodeRequire: require

# Create the require function with basic config
requireJS = require('requirejs').config(requireJSConfig)  
requireJS ['module', 'node.extend', 'crypto', 'path'], (module, extend, crypto, path) ->
    # Application configuration 
    appConfig =
        'bar':
            path:   path.dirname(module.uri)
            key:    crypto.randomBytes(64) # for doing cookie encryption

    # get a new requireJS function with CONFIG data
    requireJS = require('requirejs').config(extend(requireJSConfig, config: appConfig))
    requireJS ['bar'], (app) ->
        ###
            Load and start the server
        ###
        appServer = new app()

        #  And start the app on that interface (and port).
        appServer.start()
Run Code Online (Sandbox Code Playgroud)

在酒吧咖啡里

# bar.coffee
define ['module'], (module) ->
    # config is now available in this module
    console.log(module.config().key)
Run Code Online (Sandbox Code Playgroud)