Skip to content

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 vite
  • Adjust index.html and remove all unncessary files:

    • public/
    • counter.js
    • javascript.svg
    • main.js
    • style.css
  • Add vite.config.js file:

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.json and 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.html to .gitignore since it's not needed in GitHub repo.

  • Create a src folder 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 publish

Your package should now be available on npm respository.