Creating packages
Making your own package means writing a module, describing it in package.json, and publishing it.
In this page:
Syntax
// index.js
function functionName() {
// body
}
module.exports = { functionName };
// package.json: "name", "version", "main": "index.js"
Creating packages
A package needs a package.json with name and version and an entry file exported through module.exports. npm link lets you test it locally, and npm publish uploads it to the registry. Scoped names like @you/tool avoid name clashes.
Note:
Use the files field or .npmignore to control what gets published.
Example: Creating packages
// index.js of a tiny package
function slugify(text) {
return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
module.exports = { slugify };
// usage from another file
console.log(module.exports.slugify(" Hello, Node World! "));
// Output:
// hello-node-world
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Publishing secrets or tests by accident
- Forgetting to bump the version before publishing
- Naming clashes on the public registry
Chapter Summary
- Export through module.exports
- package.json needs name and version
- npm link tests locally
- npm publish releases it
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: