简体   繁体   English

在 node.js 中为 require 设置路径

[英]Setting a path for require in node.js

I have a folder structure like this.我有一个这样的文件夹结构。

  • include/

    • index.js
    • plugin/

      • plugin.js
      • helper.js

Where:-在哪里:-

include/index.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包括/插件/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');

I want to map the path of require in plugin.js file so that all require call should search for its module in the same directory only .我想在plugin.js文件中映射require的路径,以便所有的 require 调用都应该same directory onlysame directory only搜索其模块。

Try changing the NODE_PATH variable via the command line: 尝试通过命令行更改NODE_PATH变量:

exports NODE_PATH=directoryYouWant

If you don't want to have to change it for every other project, you could try just dynamically changing it in you .js file: 如果您不想为每个其他项目都进行更改,则可以尝试仅在.js文件中动态更改它:

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

You might be able to dynamically change the NODE_PATH environment variable: 您也许可以动态更改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;

If your wanna add /foo/bar to require:如果您想添加/foo/bar来要求:

  • by editting process.env.NODE_PATH通过编辑 process.env.NODE_PATH

then your js files should reside inside /foo/bar/node_modules/那么你的 js 文件应该位于 /foo/bar/node_modules/

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

then your js files should reside inside /foo/bar/那么你的 js 文件应该位于 /foo/bar/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM