I spent the whole weekend trying to figure out how to publish my first npm package. If you aren’t familiar, npm is a way to download prebuilt software. This week I built a calendar that allows you to change the color of specific days. I built it for a project i was working on, and realized there are other projects I could use this on too. So i decided to publish it to npm so I could reuse it in my other projects and others can use it too. Here is a link to the published package if you would like to see it.
Steps to publish
Install react vite to start a web app
npm create vite@latest
Create a directory to hold your package
I called mine “lib”
Create a file called main.js in that Directory
Add another directory that holds the Component
Export the Component in main.js
main.js should be one line and look like this
export {default as Calendar} from "./comp/calendar";
Import the Component in app.js
In your app.js file you can delete everything and import the main.js component
import {Calendar} from '@heatCalendar'
function App() {
return (
<div className="flex justify-center">
<Calendar/>
</div>
);
}
export default App
Add build to your vite.config.js file
build: {
lib: {
entry: resolve(__dirname, "lib/main.js"),
name: "simple-react-HeatCalendar",
formats: ["es", "cjs"],
fileName: (format) => `heatCalendar.${format}.js`,
},
rollupOptions: {
external: ["react", "react-dom", "react/jsx-runtime"],
output: {
globals: {
react: "React",
"react-dom": "ReactDOM",
"react/jsx-runtime": "react/jsx-runtime",
},
},
},
Install react and react-dom,
"peerDependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
Add Scripts to package.json
"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && vite build",
"publish": "npm run build"
},
Add Files, Main, Module and Exports to package.json
"files": [
"dist",
"README.md"
],
"main": "./dist/heatCalendar.cjs.js",
"module": "./dist/heatCalendar.es.js",
"exports": {
".": {
"import": "./dist/heatCalendar.es.js",
"require": "./dist/heatCalendar.cjs.js"
}
},
Add Resolve to the
vite.config.js
for Local ImportsOnce its published to npm it will be imported as the package name
resolve: {
alias: {
"@heatCalendar": resolve(__dirname, "./lib/main"),
},
},
Publish your Package!
Run the following commands to build the project and then publish it:
npm run publish
npm publish
You may need to create an account with npm to publish, but when you run
npm publish
, it will walk you through that.Once I understood how this process works, it was so easy to implement. And by doing it once, makes it easy to replicate. Here is my github repo for the code if you need a reference. Otherwise, I’m very excited to publish something that other people can use and I can use in my other projects too. If there are any questions let me know.
Au Revoir,