问题描述
我写了一个简单的 npm 模块来预编译我的车把模板,当使用 django 压缩器对一些客户端组件进行后处理时,发现我需要用几个 js 文件来发送 npm 模块.
I wrote a simple npm module to precompile my handlebars templates when using django compressor to do post-processing for some client side components and found that I need to ship the npm module with a few js files.
目前我只是假设没有人使用全局标志安装它,因为我已经在 npm 模块本身中硬编码"了这些依赖项的路径
Currently I just assume no one is installing this with the global flag because I've "hard coded" the path to these dependencies in the npm module itself
我的 npm 模块的示例布局
/
*/bin
*/lib/main.js
*/vendor/ember.js
/
* /bin
* /lib/main.js
* /vendor/ember.js
现在在 main.js 中我想使用 ember.js 文件......目前我的硬编码方法看起来像这样
Now inside main.js I want to use the ember.js file ... currently my hard coded approach looks like this
var emberjs = fs.readFileSync('node_modules/django-ember-precompile/vendor/ember.js', 'utf8');
再次 - 这只是因为我假设您将其安装在本地,但我想认为 node.js 有一种更合法的方式来获取本地嵌入的文件
Again -this only works because I assume you install it local but I'd like to think node.js has a more legit way to get locally embedded files
有人知道我如何改进它以使其更加全球"友好吗?
Anyone know how I can improve this to be more "global" friendly?
推荐答案
您可以做的是获取当前文件的目录,并使您的文件路径与该目录相关.
What you can do is get the directory of the current file and make your file paths relative to that.
var path = require('path')
, fs = require('fs');
var vendor = path.join(path.dirname(fs.realpathSync(__filename)), '../vendor');
var emberjs = fs.readFileSync(vendor + '/ember.js', 'utf8');
希望有帮助!
这篇关于如何在 npm 模块中引用本地文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!