1,817 words, 10 minutes read time.

If you’re like most seasoned web or SharePoint developers, you probably appreciate the satisfaction that comes from writing code that’s not only effective for a single project but is also versatile enough to be reused across multiple solutions. Creating modular, shareable pieces of functionality feels a lot like crafting your own toolkit—one that you can rely on instead of repeatedly borrowing or rewriting someone else’s work.
That’s exactly what this deep dive is about: building a SharePoint Framework (SPFx) component that you can package into an NPM library, ready to be pulled into any future project you (or your team) might tackle. In the process, we’ll walk through setting up a complete “Hello World” demo that ties all the concepts together, so by the time you finish, you’ll have the groundwork laid for building professional, maintainable, and portable solutions.
The document kicks off with foundational concepts to ensure we’re on the same page technically. From there, it moves into practical application by guiding you through the steps of creating a simple SPFx web part, developing a utility library in TypeScript, publishing it to NPM (or using it locally if you prefer), and finally consuming that package in your SPFx component. This article wraps up with some best practices on publishing, versioning, and common mistakes developers make so you can avoid them.
Let’s start by discussing why building NPM-packaged SPFx components makes sense in the first place.
Understanding Why SPFx and NPM Make a Powerful Combination
SharePoint Framework, often referred to as SPFx, is Microsoft’s preferred model for building client-side web parts and extensions for SharePoint Online and, with certain compatibility considerations, for on-premises SharePoint too. At its core, SPFx isn’t very different from other modern JavaScript frameworks. It relies heavily on familiar tools like TypeScript, React (or any JavaScript framework you’re comfortable with), and Webpack for bundling.
A typical SPFx solution includes a manifest file that tells SharePoint where and how to load it, TypeScript source files that implement the UI and logic, and a build pipeline usually orchestrated through Gulp. This makes it approachable for most developers who already work in the JavaScript ecosystem.
But if you’ve been in the trenches of large enterprise projects, you know code duplication can be a serious time sink. If you build a neat date formatter or API abstraction in one SPFx solution, you might end up copying it into three other projects. Maintaining consistency, squashing bugs, or adding enhancements then becomes a nightmare across disparate codebases.
This is where publishing reusable functionality as an NPM package becomes an obvious move. Once your business logic, helper utilities, or UI components are encapsulated in a package, you can simply run npm install your-package-name in any SPFx (or general web) project. This approach consolidates maintenance, simplifies bug fixes, and positions your team for much smoother upgrades or feature expansions down the road.
In short, SPFx gives you the mechanism to build SharePoint customizations, and NPM gives you the power to modularize, distribute, and maintain those customizations cleanly and efficiently.
Laying a Solid Technical Foundation
Before we start writing any code, it’s worth ensuring your local environment is properly configured. SharePoint Framework has some version-specific quirks that can cause frustration if overlooked. Ideally, you’ll have Node.js installed at version 16.x because many SPFx versions are still tuned to work best with that Node range. Installing a newer Node version may work, but often leads to subtle incompatibility problems with gulp tasks or certain SPFx dependencies.
You’ll also need Yeoman (yo) and Microsoft’s official SPFx generator. If you don’t already have them installed, you can add them globally by running:
npm install -g yo @microsoft/generator-sharepoint
Likewise, install Gulp CLI, which will drive your build and serve processes:
npm install -g gulp
Although it’s optional, installing TypeScript globally can also streamline local builds for your utility library:
npm install -g typescript
A modern code editor such as Visual Studio Code is highly recommended for its TypeScript integration, intellisense, and debugging capabilities. With your environment prepped, you’re ready to move from concept to practical implementation.
Building a Basic SPFx “Hello World” Web Part
To ground all these ideas, we’ll start by creating a simple SPFx web part. This will serve as the consumer of the reusable NPM package we’ll build shortly. Start by creating a fresh project directory and using Yeoman to scaffold a new SPFx solution:
mkdir hello-world-spfx
cd hello-world-spfx
yo @microsoft/sharepoint
Yeoman will walk you through a series of prompts. You can provide values like these for a straightforward demo:
Solution Name: hello-world-spfx
Web Part Name: HelloWorld
Framework: React
Description: A simple Hello World SPFx web part
Once generation finishes, install dependencies and run the local dev server:
npm install
gulp serve
Your local SharePoint Workbench, often accessible at a URL similar to https://<your-dev-site>/_layouts/15/workbench.aspx, will load. You should be able to add the HelloWorld web part onto the page. At this point, the default component will render some basic placeholder text.
To customize it, open your project in VS Code, navigate to src/webparts/helloWorld/components/HelloWorld.tsx, and replace the JSX in the render method with something more visually distinctive:
return (
<div style={{ padding: '20px', background: '#0078d4', color: '#fff' }}>
<h2>Hello, world!</h2>
<p>This is your first SPFx web part.</p>
</div>
);
Restart the dev server with gulp serve and verify that your styled greeting appears. This completes the core setup of your SPFx consumer project.
Creating a Simple Utility Library to Publish on NPM
Now comes the interesting part: creating a standalone TypeScript library that could be published to NPM. This small package will contain functionality we can reuse across SPFx projects.
Outside your SPFx solution directory, set up a new directory for your utility library and initialize it:
mkdir hello-world-utils
cd hello-world-utils
npm init -y
This creates a package.json with default values. Next, establish your TypeScript source by creating a src folder and an index.ts file inside it:
export function getGreeting(name: string): string {
return `Hello, ${name}!`;
}
To compile TypeScript into distributable JavaScript, install TypeScript locally and initialize a config file:
npm install typescript --save-dev
npx tsc --init
Edit the generated tsconfig.json to set appropriate compilation targets and ensure type definitions are produced:
{
"compilerOptions": {
"outDir": "./dist",
"declaration": true,
"module": "commonjs",
"target": "es6",
"strict": true,
"esModuleInterop": true
},
"include": ["src"]
}
Now you can compile your library:
npx tsc
This generates JavaScript and type definition files under dist/, making it suitable for direct import into other TypeScript projects.
Installing and Using the Library Inside Your SPFx Web Part
You have two primary options to make this library available to your SPFx project. If you want to keep things local and avoid publishing it publicly right now, simply install it from your filesystem:
npm install ../hello-world-utils
Alternatively, if you decide to share it with others or across different environments, log in to NPM and publish it:
npm login
npm publish --access public
Once installed in your SPFx solution, import and use it by opening HelloWorld.tsx and adding:
import * as React from 'react';
import { getGreeting } from 'hello-world-utils';
const HelloWorld: React.FC = () => {
return (
<div style={{ padding: '20px', background: '#0078d4', color: '#fff' }}>
<h2>{getGreeting('SharePoint Developer')}</h2>
<p>This greeting comes from your reusable NPM package.</p>
</div>
);
};
export default HelloWorld;
Restart the local server using gulp serve to see your new greeting, dynamically generated through your modular NPM library.
Strategies for Versioning, Publishing, and Keeping It Maintainable
Once you start building more packages, it’s tempting to publish frequent updates without much ceremony. However, applying consistent versioning strategies saves headaches later, particularly if multiple projects depend on your package. Stick with semantic versioning by incrementing patch, minor, or major versions intentionally, using npm version patch, npm version minor, or npm version major.
Document your library well, ideally with examples in a README. This helps you and any collaborators understand usage months or years down the line. If you expect rapid growth into multiple shared utilities, consider tools like lerna or nx for monorepo management, which can streamline cross-package dependency updates and publishing workflows.
Testing your utility outside SPFx first is also a smart habit. Write a quick Node script that imports your function and logs output to ensure it behaves correctly without SPFx’s build pipeline complexities. This often reveals subtle bugs or missing type definitions early.
Avoiding Common Pitfalls When Combining SPFx and External NPM Packages
There are several issues developers frequently encounter. One is mismatched React versions. Many SPFx versions still use React 16.8 internally, so if your library is compiled against React 18 or pulls in React hooks that are incompatible, you could see cryptic runtime errors. Keeping peerDependencies aligned in your package.json helps mitigate these problems.
Always ensure your TypeScript build generates .d.ts files. Without them, your SPFx consumer project will lose intellisense and type safety, defeating one of the main reasons to use TypeScript. Additionally, if your utilities are only meant for internal use, you might prefer to scope them under a private namespace such as @company/package-name to prevent accidental public exposure.
Wrapping It All Up With a Look to the Future
At this point, you’ve learned not just how to build a SharePoint Framework web part, but also how to architect supporting libraries that live in NPM and can be pulled into any future project. This approach means you’re no longer reinventing the wheel with each new solution. You’re setting yourself up for cleaner maintenance, easier bug fixes, and a development process that scales with your team’s evolving needs.
This modular strategy doesn’t stop with simple “Hello World” examples. It opens doors to packaging up entire UI components, data-fetching services, or even full design systems, all of which can be dropped into new SPFx projects or extended to any React environment down the line.
Let’s Keep This Conversation Going
I’d genuinely love to hear what kinds of SPFx components or reusable NPM packages you’re building, experimenting with, or perhaps even struggling to get right. Drop a comment below if this is published on a blog, sign up for our newsletter if you’d like more in-depth guides like this in your inbox, or feel free to reach out to me directly. I’m always glad to swap stories about SharePoint adventures, TypeScript frustrations, or why modular code is still the best insurance policy you can write for your future projects.
Sources
- SharePoint Framework Overview – Microsoft Docs
- Set up your SharePoint Framework development environment – Microsoft Docs
- Build your first SPFx web part – Microsoft Docs
- NPM Official Website
- Yarn Documentation
- Webpack Concepts
- Jest Testing Framework
- TypeScript Documentation
- React Official Docs
- SPFx Library Components – Microsoft Docs
- GitHub – Where the world builds software
- ESLint for Code Quality
- Prettier Code Formatter
- Office UI Fabric React on NPM
- Google SEO Starter Guide
Disclaimer:
The views and opinions expressed in this post are solely those of the author. The information provided is based on personal research, experience, and understanding of the subject matter at the time of writing. Readers should consult relevant experts or authorities for specific guidance related to their unique situations.
