
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 typescriptStep 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
buildScript
Thebuildscript ensures that your TypeScript code is transpiled into JavaScript before publishing the package. Here's what happens:
"build": "rimraf dist && tsc"rimraf dist: Cleans thedistdirectory, ensuring no leftover files from a previous build.tsc: Runs the TypeScript compiler (tsc) to transpile the source files from thesrcdirectory into JavaScript files in thedistdirectory. It also generates type declaration files (.d.ts) as specified intsconfig.json.prepublishScript
Theprepublishscript 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
srcdirectory:
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
/distCreate .npmignore:
node_modules/
src/
tsconfig.jsonStep 9: Directory Structure
Your package directory should now look like this:
package-name/
├── src/
│ ├── admin.schema.ts
│ ├── index.ts
├── package.json
├── tsconfig.json
├── .gitignore
├── .npmignoreStep 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 mainStep 11: Versioning Your Package
Use the following commands to update the version of your package:
- Patch:
npm run patch→ Updates1.0.0to1.0.1 - Minor:
npm run minor→ Updates1.0.0to1.1.0 - Major:
npm run major→ Updates1.0.0to2.0.0
Step 12: Publish Your Package
Run the following commands to publish your package:
- For the first publish:
npm publish --access public2. For subsequent updates:
npm publishConclusion
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! ๐