← Back to Node.js Course | Chapter 3: npm & Packages | Lesson 6 of 7

Creating packages

Making your own package means writing a module, describing it in package.json, and publishing it.

In this page:

  1. Creating packages
Syntax
javascript
// 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

javascript
// 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
  1. Publishing secrets or tests by accident
  2. Forgetting to bump the version before publishing
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.