Create and Publish NPM Package (using vite)
NOTE
There are multiple ways to create an NPM package, but this guide uses vite
Pre-requisites
- Node.js
- YARN package manager
Create a package
- Create a new Vite project using
yarn:
sh
yarn create viteAdjust
index.htmland remove all unncessary files:- public/
- counter.js
- javascript.svg
- main.js
- style.css
Add
vite.config.jsfile:
js
import path from "path";
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import * as pkg from "./package.json";
const VERSION = pkg.version;
export default {
build: {
copyPublicDir: false,
lib: {
entry: path.resolve(__dirname, "src", "index.js"),
name: "DistName",
fileName: "distFileName"
}
},
define: {
VERSION: JSON.stringify(VERSION),
},
plugins: [
cssInjectedByJsPlugin(),
]
};- Improve
package.jsonand include following:
json
{
// ...
// distFileName should match with vite.config.js
"devDependencies": {
"vite": "^5.2.0",
"vite-plugin-css-injected-by-js": "^3.5.1"
},
"files": [
"dist"
],
"main": "./dist/distFileName.umd.js",
"module": "./dist/distFileName.mjs",
"exports": {
".": {
"import": "./dist/distFileName.mjs",
"require": "./dist/distFileName.umd.js"
}
}
}Add
index.htmlto.gitignoresince it's not needed in GitHub repo.Create a
srcfolder and add necessary code files under it.Install dependent packages using
yarn install.Run dev server using
yarn dev.
Publish to NPM
- Log into
npm:
sh
npm login- Publish the package:
sh
npm publishYour package should now be available on npm respository.
