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

查看:31
本文介绍了如何让 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('../')

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

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天全站免登陆