简体   繁体   English

Node.js在npm模块中使用单文件依赖

[英]Node.js use single-file dependency in npm module

I have a single file (either a .js or .node generated with C++, but works the same) that I can use in node.js by calling: 我有一个文件(可以使用C ++生成的.js或.node,但工作原理相同),可以通过调用在node.js中使用:

var addon = require("./addon");

It's not an official package or anything; 它不是官方软件包或其他任何东西; it has no package.json (and I want to keep it that way). 它没有package.json(我想保持这种方式)。

This above code works fine if I run it in a simple node.js application, but how do I include it in a node.js library? 如果我在简单的node.js应用程序中运行上述代码,则可以正常工作,但是如何将其包含在node.js库中? For example: 例如:

exports.addon = require("./addon")

This doesn't seem to work, I tried changing the package.json: 这似乎不起作用,我尝试更改package.json:

"dependencies": {
    "addon": "file:./addon.node",
}

but when I use 但是当我用的时候

require("addon");

later it says it can't be found. 后来它说找不到。 [ EDIT : after I run npm publish and then npm -i mymodule in another file] [ 编辑 :在我运行npm publish然后在另一个文件中运行npm -i mymodule之后]

Am I missing something? 我想念什么吗?

Assuming you are writing your own library and want to include you add-on there, I would build a file structure like this: 假设您正在编写自己的库,并希望在其中包含附加组件,那么我将构建一个像这样的文件结构:

index.js
addon/cpp-generated.js
addon/other.js
...

Then from index.js you can just do: 然后从index.js您可以执行以下操作:

const cpp_generated = require('./addon/cpp-generated')

I've only used .js extensions. 我只用了.js扩展名。 You need to change a configuration file to allow for new extensions (like the .node that you mention.) 您需要更改配置文件以允许新的扩展名(例如您提到的.node 。)

There is no need to mention the file in your package.json for things to work. 无需在package.json提及文件即可正常工作。 It may be needed there if you run a build, although it should get included because of the require() statement anyway. 如果您运行构建,则可能需要在此处进行构建,尽管无论如何,由于require()语句应将其包含在内。

So it looks like you're doing it right except maybe for the extension (your example shows .node .) 因此,除了扩展名(您的示例显示.node )外,您似乎做对了。

And to make sure it gets published, I would add it to the list of files: 为了确保它被发布,我将其添加到文件列表中:

"files": [
    "index.js",
    "addon/cpp-generated.js",
    ...
]

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

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