如何使node.js要求绝对? (而不是亲戚) [英] How to make node.js require absolute? (instead of relative)

查看:64
本文介绍了如何使node.js要求绝对? (而不是亲戚)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想始终以我项目的根目录而不是相对于当前模块的目录来要求我的文件.

I would like to require my files always by the root of my project and not relative to the current module.

例如,如果您查看 https://github. com/visionmedia/express/blob/2820f2227de0229c5d7f28009aa432f9f3a7b5f9/examples/downloads/app.js 第6行,您将看到

For example if you look at https://github.com/visionmedia/express/blob/2820f2227de0229c5d7f28009aa432f9f3a7b5f9/examples/downloads/app.js line 6 you will see

express = require('../../')

那真是糟糕的IMO.想象一下,我只想将我所有的例子都更靠近根源.那将是不可能的,因为我将不得不在每个示例中多次更新30多个示例.为此:

That's really bad IMO. Imagine I would like to put all my examples closer to the root only by one level. That would be impossible, because I would have to update more than 30 examples and many times within each example. To this:

express = require('../')

我的解决方案是为基于root的情况提供特殊情况:如果字符串以$开头,则它相对于项目的根文件夹.

My solution would be to have a special case for root based: if a string starts with an $ then it's relative to the root folder of the project.

感谢您的帮助,谢谢

现在,我正在使用require.js,它允许您以一种方式编写并且可以在客户端和服务器上运行. Require.js还允许您创建自定义路径.

Now I'm using require.js which allows you to write in one way and works both on client and on server. Require.js also allows you to create custom paths.

现在,我移至webpack + gulp,并使用Enhanced-require处理服务器端的模块.此处查看原理: http://hackhat.com /p/110/module-loader-webpack-vs-requirejs-vs-browserify/

Now I moved to webpack + gulp and I use enhanced-require to handle modules on the server side. See here the rationale: http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/

推荐答案

那又如何:

var myModule = require.main.require('./path/to/module');

它需要文件,就好像它是主js文件中的必需文件一样,因此只要您的主js文件位于项目的根目录下,它就可以很好地工作.

It requires the file as if it were required from the main js file, so it works pretty well as long as your main js file is at the root of your project... and that's something I appreciate.

这篇关于如何使node.js要求绝对? (而不是亲戚)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆