【问题标题】:Setting a path for require in node.js在 node.js 中为 require 设置路径
【发布时间】:2015-11-15 16:55:21
【问题描述】:

我有一个这样的文件夹结构。

  • include/

    • index.js
    • plugin/

      • plugin.js
      • helper.js

地点:-

包含/index.js

//Function for mapping the path of  "require" statement in  the plugin.js file.

var mapRequirePath = function(){

    var plugins = require('./plugin/plugin');
     return plugins;
}

//Now call the plugins..
var plugin = mapRequirePath();

include/plugin/plugin.js

    /*
       I want all four require statements to point to the same file location '/include/plugin/helper.js'

      i.e search in the same folder location for module irrespective of the '../' or '../../' present in the require statement
    */

    var helper1 = require('./helper');
    var helper2 = require('helper');
    var helper3 = require('../../helper');
    var helper4 = require('../helper');

我想在plugin.js 文件中映射require 的路径,这样所有的require 调用都应该在same directory only 中搜索它的模块。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    如果您想将 /foo/bar 添加到要求:

    • 通过编辑 process.env.NODE_PATH

    那么你的 js 文件应该位于 /foo/bar/node_modules/

    process.env.NODE_PATH = '/foo/bar' + ':' + process.env.NODE_PATH;
    
    • 通过编辑module.paths

    那么你的 js 文件应该位于 /foo/bar/

    module.paths.push('/foo/bar');
    

    【讨论】:

      【解决方案2】:

      您也许可以动态更改 NODE_PATH 环境变量:

      // First take a backup:
      var _NODE_PATH = process.env.NODE_PATH;
      // Add /includes/plugin to the path, also note that we need to support 
      //   `require('../hello.js')`. We can do that by adding /includes/plugin/a, 
      //   /includes/plugin/a/b, etc.. to the list
      process.env.NODE_PATH+=':/includes/plugin:/includes/plugin/a';
      // Do your think...
      require('./plugins/plugin');
      // Restore NODE_PATH 
      process.env.NODE_PATH = _NODE_PATH;
      

      【讨论】:

      • 这似乎不再起作用了。 process.env.NODE_PATH 为我返回 undefined。但module.paths 返回搜索路径。这可以更改,但仅限于单个模块,我希望它适用于整个应用程序。
      【解决方案3】:

      尝试通过命令行更改 NODE_PATH 变量:

      exports NODE_PATH=directoryYouWant
      

      如果您不想为每个其他项目更改它,您可以尝试在 .js 文件中动态更改它:

      var currentNodePath = process.env.NODE_PATH;
      process.env.NODE_PATH = directoryYouWant;
      //do stuff then change it back
      process.env.NODE_PATH = currentNodePath;
      

      【讨论】:

      • 这将改变所有文件系统的节点路径。我只想在 require 内部调用 /include/plugin folder 的情况下更改它
      • 我知道我们有类似的想法 :)
      猜你喜欢
      • 1970-01-01
      • 2013-05-21
      • 2018-12-21
      • 2010-12-16
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 2012-10-10
      相关资源
      最近更新 更多