Skip to main content

How to Make a Public NPM Package of NestJS Mongoose Schema

Building microservices often requires sharing database schemas across projects. As a NestJS developer, I struggled to figure out the best way to create a reusable package for my Mongoose schemas. After some trial and error, I finally cracked the process. Here’s a step-by-step guide to help you do the same.


Step 1: Create an NPM Account

Before you begin, ensure you have an NPM account. Public packages are free, while private ones require a subscription. For this tutorial, we’ll use a public package.


Step 2: Initialize Your Package

  • Open your terminal and run:
mkdir package-name 
cd package-name
npm init
  • Follow the prompts to set up your package.

You need to add a unique name to publish your package.


Step 3: Install Dependencies

Run the following commands to install the required dependencies:

npm install @nestjs/common rxjs reflect-metadata
npm install -D @types/node rimraf typescript

Step 4: Update package.json

Edit your package.json to look like this:

{
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rimraf dist && tsc",
"prepublish": "npm run build",
"patch": "yarn version --patch",
"minor": "yarn version --minor",
"major": "yarn version --major"
}
}

This configuration:

  • Specifies the entry points for the package.
  • Adds build and versioning scripts for easy maintenance.

Understanding the build and prepublish Scripts

  • build Script
    The build script ensures that your TypeScript code is transpiled into JavaScript before publishing the package. Here's what happens:
"build": "rimraf dist && tsc"
  • rimraf dist: Cleans the dist directory, ensuring no leftover files from a previous build.
  • tsc: Runs the TypeScript compiler (tsc) to transpile the source files from the src directory into JavaScript files in the dist directory. It also generates type declaration files (.d.ts) as specified in tsconfig.json.
  • prepublish Script
    The prepublish script runs automatically before your package is published to the NPM registry. This ensures that your package is always published with a fresh and clean build.
"prepublish": "npm run build"

When you run npm publish, the prepublish script triggers the build process, compiling your TypeScript files and cleaning up any stale builds beforehand.


Step 5: Configure TypeScript

Create a tsconfig.json file and paste the following:

{
"compilerOptions": {
"experimentalDecorators": true,
"target": "es2017",
"module": "commonjs",
"lib": ["es2017", "es7", "es6"],
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true
},
"exclude": ["node_modules", "dist"]
}

Step 6: Add Your Schema

  • Create a src directory:
mkdir src
  • Add a schema file, for example admin.schema.ts:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { options } from './options';

@Schema(options)
export class Admin {
@Prop({ required: true })
name: string;

@Prop({ required: true, unique: true })
email: string;

@Prop({ required: true })
password: string;

@Prop({
required: true,
enum: ['active', 'deleted'],
default: 'active',
})
status: string;
}

export const AdminSchema = SchemaFactory.createForClass(Admin);

Step 7: Create index.ts

In the src directory, create an index.ts file and export your schema:

export * from './admin.schema';

If you add more schemas, include their exports here.


Step 8: Add .gitignore and .npmignore

Create .gitignore:

/node_modules
/dist

Create .npmignore:

node_modules/
src/
tsconfig.json

Step 9: Directory Structure

Your package directory should now look like this:

package-name/
├── src/
│ ├── admin.schema.ts
│ ├── index.ts
├── package.json
├── tsconfig.json
├── .gitignore
├── .npmignore

Step 10: Push Your Code to GitHub

Initialize a Git repository and push your code to GitHub:

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin <your-repo-url>
git push -u origin main

Step 11: Versioning Your Package

Use the following commands to update the version of your package:

  • Patch: npm run patch → Updates 1.0.0 to 1.0.1
  • Minor: npm run minor → Updates 1.0.0 to 1.1.0
  • Major: npm run major → Updates 1.0.0 to 2.0.0

Step 12: Publish Your Package

Run the following commands to publish your package:

  1. For the first publish:
npm publish --access public

2. For subsequent updates:

npm publish

Conclusion

That’s it! You’ve successfully created and published a reusable NPM package for your NestJS Mongoose schemas.

You can now use this package across multiple projects and update it as needed.

Happy coding! ๐Ÿš€

    Popular posts from this blog

    Xcode and iOS Version Mismatch: Troubleshooting "Incompatible Build Number" Errors

    Have you ever encountered a frustrating error while trying to run your iOS app in Xcode, leaving you scratching your head? A common issue arises when your device's iOS version is too new for the Xcode version you're using. This often manifests as an "incompatible build number" error, and looks like this: DVTDeviceOperation: Encountered a build number "" that is incompatible with DVTBuildVersion. This usually happens when you are testing with beta versions of either iOS or Xcode, and can prevent Xcode from properly compiling your storyboards. Let's explore why this occurs and what you can do to resolve it. Why This Error Occurs The core problem lies in the mismatch between the iOS version on your test device and the Software Development Kit (SDK) supported by your Xcode installation. Xcode uses the SDK to understand how to build and run apps for specific iOS versions. When your device runs a newer iOS version than Xcode anticipates, Xcode mi...

    How to Fix the “Invariant Violation: TurboModuleRegistry.getEnforcing(…): ‘RNCWebView’ Could Not Be Found” Error in React Native

    When working with React Native, especially when integrating additional libraries like react-native-signature-canvas , encountering errors can be frustrating. One such error is: Invariant Violation: TurboModuleRegistry. getEnforcing (...): 'RNCWebView' could not be found This error often occurs when the necessary dependencies for a module are not properly linked or when the environment you’re using doesn’t support the required native modules. Here’s a breakdown of how I encountered and resolved this issue. The Problem I was working on a React Native project where I needed to add the react-native-signature-canvas library to capture user signatures. The installation process seemed straightforward: Installed the package: npm install react-native-signature- canvas 2. Since react-native-signature-canvas depends on react-native-webview , I also installed the WebView package: npm install react- native -webview 3. I navigated to the iOS directory and ran: cd ios pod install Everythi...

    Fixing FirebaseMessagingError: Requested entity was not found.

    If you’re working with Firebase Cloud Messaging (FCM) and encounter the error: FirebaseMessagingError: Requested entity was not found. with the error code: messaging/registration-token-not-registered this means that the FCM registration token is invalid, expired, or unregistered . This issue can prevent push notifications from being delivered to users. ๐Ÿ” Possible Causes & Solutions 1️⃣ Invalid or Expired FCM Token FCM tokens are not permanent and may expire over time. If you’re storing tokens in your database, some might be outdated. ✅ Solution: Remove invalid tokens from your database when sending push notifications. Refresh and store the latest FCM token when the app starts. Example: Automatically Refresh Token firebase. messaging (). onTokenRefresh ( ( newToken ) => { // Send newToken to your backend and update the stored token }); 2️⃣ Token Unregistered on Client Device A token might become unregistered if: The app is uninstalled on the user’s device. ...