
How to Create Your Own npm Library
How to Create Your Own npm Library 관련
Creating your own npm library is a great way to share reusable code, contribute to the open-source community, or even streamline development across multiple projects. In this section, we’ll walk through the step-by-step process of setting up, coding, and preparing a library for publishing on npm.
Setting Up a New Package
Before writing code, you need to set up an npm package. Follow these steps:
Step 1: Create a New Project Folder
mkdir my-awesome-library
cd my-awesome-library
Step 2: Initialize npm
Run the following command to create a package.json
file:
npm init
You will be prompted to enter details such as:
- Package name
- Version
- Description
- Entry point (default:
index.js
) - Author
- License
💡 To skip the prompts and create a default package.json
, use:
npm init -y
Writing Modular and Reusable Code
Now, let’s create a simple utility library that provides a function to format dates.
Step 3: Create an index.js
File
Inside the project folder, create a file named index.js
and add the following code:
function formatDate(date) {
if (!(date instanceof Date)) {
throw new Error("Invalid date");
}
return date.toISOString().split("T")[0];
}
module.exports = { formatDate };
Adding Dependencies and Peer Dependencies
Your library might depend on external packages. For example, let’s use date-fns for better date formatting.
To install it as a dependency, run:
npm install date-fns
Then, modify index.js
to use date-fns
:
const { format } = require("date-fns");
function formatDate(date) {
if (!(date instanceof Date)) {
throw new Error("Invalid date");
}
return format(date, "yyyy-MM-dd");
}
module.exports = { formatDate };
If you're creating a React-specific library, you should add React as a peer dependency:
npm install react --save-peer
This ensures users of your library install React separately, preventing version conflicts.
Before publishing, you should test how your package works when installed as a dependency.
Step 4: Link the Package Locally
Run the following command in your package folder:
npm link
Then, in another project where you want to use your package, navigate to that project and run:
npm link my-awesome-library
Now, you can import and use your function:
const { formatDate } = require("my-awesome-library");
console.log(formatDate(new Date())); // Output: 2025-02-04 (or the current date)
Once you're happy with your package, it's time to publish it on npm.