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

查看:36
本文介绍了如何使 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 并使用增强的需求来处理服务器端的模块.请参阅此处的理由: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天全站免登陆