简体   繁体   中英

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:

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).

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? For example:

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

This doesn't seem to work, I tried changing the 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]

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:

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

I've only used .js extensions. You need to change a configuration file to allow for new extensions (like the .node that you mention.)

There is no need to mention the file in your package.json for things to work. It may be needed there if you run a build, although it should get included because of the require() statement anyway.

So it looks like you're doing it right except maybe for the extension (your example shows .node .)

And to make sure it gets published, I would add it to the list of files:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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