Node.js动态相对需要路径

时间:2015-05-05 12:51:04

标签: node.js require

我需要能够在动态相对路径上使用require() - 这意味着相对路径需要根据当前环境进行更改。

此类情况的最佳做法是什么?

我想到了这样的事情:

var module = require(process.env.MY_MODULES_PATH + '/my-module');

但是环境变量不是很方便。

还有其他可能吗?

  • 也许使用package.json安装后脚本为我设置环境变量?
  • 也许在我不了解的节点中有一个内置的解决方案?

修改

我刚才意识到这是require()"嘲笑"的一个特例。例如,对于单元测试如何模拟require()是否有最佳实践?

3 个答案:

答案 0 :(得分:0)

MockedRequire.js

var path = require('path');

function MockedRequire(module) {
    return require(path.join('/path/to/modules', module));
}

module.exports = MockedRequire;

使用:

var mymodule = require('./MockedRequire.js')('mymodule');

说实话,我实际上并没有对此进行测试,但它应该没有问题。

答案 1 :(得分:0)

我建议使用配置加载程序。它将根据您的NODE_ENV变量选择路径,但它比您建议的更清晰,因为您将所有特定于环境的配置保存在单个外部文件中。

示例:

答案 2 :(得分:0)

Webpack需要知道在编译时要捆绑哪些文件,但表达式只在运行时给出值,需要require.context

/* If structure like:

    src -
         |
          -- index.js (where these code deploy)
         |
          -- assets - 
                     |
                      --img
*/  


let assetsPath = require.context('./assets/img', false, /\.(png|jpe?g|svg)$/); 

// See where is the image after bundling.
// console.log(assetsPath('./MyImage.png'));
// In fact you could put all the images you want in './assets/img', and access it by index: './otherImg.jpg' 
var newelement = {
    "id": doc.id,
    "background": assetsPath('./MyImage.png');
};
相关问题