javascript 当配置依赖于 RequireJS 时,使用 RequireJS 配置模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14518569/
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 21:50:23  来源:igfitidea点击:

Configuring modules with RequireJS when config depends on RequireJS

javascriptnode.jsrequirejs

提问by greTech

Apologies if I have missed this in the docs. Basically I want to use the RequireJS module configuration feature. I would like to centrally manage the config values given to modules in a package.

如果我在文档中遗漏了这一点,我深表歉意。基本上我想使用 RequireJS 模块配置功能。我想集中管理提供给包中模块的配置值。

This is an example from the docs:

这是文档中的一个示例:

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;
});

My problem is that my configuration info will be a little more complex, and will itself have dependencies. I would like to do:

我的问题是我的配置信息会稍微复杂一些,并且本身会有依赖关系。我想要做:

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

Where variables in my config need to use requireJS to evaluate.

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

To me it would make sense for there to be a logical separation between the RequireJS configuration - the config necessary to load modules - and the user's module configuration. But I am currently struggling to find this :(

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

采纳答案by greTech

Having thought about this a little more I have come up with a workaround. It is not particularly pretty but it does seem to work.

多想了一点,我想出了一个解决方法。它不是特别漂亮,但似乎确实有效。

I simply do requireJS(...) twice, first to create the config, and second to load the application modules with the config..

我简单地执行了两次 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()

And in bar.coffee

在 bar.coffee

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

回答by jrburke

For this sort of solution, I would have the module depend on a "config" module that you can swap for a different one using paths config. So if "bar" needed some config, "bar.js" would look like:

对于这种解决方案,我会让模块依赖于一个“配置”模块,您可以使用路径配置替换另一个模块。所以如果“bar”需要一些配置,“bar.js”看起来像:

define(['barConfig'], function (config) {
});

Then barConfig.js could have your other dependencies:

然后 barConfig.js 可以拥有您的其他依赖项:

define(['crypto'], function (crypto) {
    return {
      key: crypto.randomBytes(64)
    }
});

Then, if you needed different configs for say, production vs. dev, use paths config to map barConfig to other values:

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

requirejs.config({
  paths: {
    barConfig: 'barConfig-prod'
  }
});

回答by Felix

I think the proper way to do this is to make a config module...

我认为这样做的正确方法是制作一个配置模块......

// config.js
define(['module', 'path', 'crypto'], function(module, path, crypto) {
    return {
        path: path.dirname(module.uri)
        key: crypto.randomBytes(64)
    };
}); 

Then use it in other modules...

然后在其他模块中使用它......

// bar.js
define(['config'], function (config) {
    var key = config.key;
});

You can then make it as complicated as you like!

然后,您可以根据需要使其变得复杂!

EDIT: You could pollute the global namespace for this special class...

编辑:您可能会污染这个特殊类的全局命名空间...

define(['module', 'path', 'crypto'], function(module, path, crypto) {
    window.config = {
        path: path.dirname(module.uri)
        key: crypto.randomBytes(64)
    };
}); 

Add it to the top level require call:

将其添加到顶层 require 调用:

require(['config', 'main']);

Then you can use it without always adding it to your define:

然后你可以使用它而不必总是将它添加到你的定义中:

// bar.js
define([], function() {
    var key = config.key;
});

回答by f1lt3r

Riffing on what @jrburke is saying, I found the following pattern to be quite useful: define a config module and it's dependencies in the main.jsjust before the invocation of require.config().

根据@jrburke 的说法,我发现以下模式非常有用:main.js在调用require.config().

main.js

主文件

define('config', ['crypto'], function (crypto) {
  return {
    'bar': {
      key: crypto.randomBytes(64)
    },
  };
});

requirejs.config({
  deps: ['app'],
});

app.js

应用程序.js

require(['config'], function (config){

  // outputs value of: crypto.bar.key
  console.log(config.bar.key);
});

Plnkr Demo: http://plnkr.co/edit/I35bEgaazEAMD0u4cNuj

Plnkr 演示:http://plnkr.co/edit/I35bEgaazEAMD0u4cNuj