npm Package Creation
Description
Documentation on how to modify the package.json and vite.config.js files, and on how to create the index.js file.
Project Structure
Before starting, make sure you have a project structure like this:
my-package/├── src/│ └── index.js├── package.json├── vite.config.js└── README.mdindex.js
Create an index.js file inside the ./src folder. Here, we will export the files we need from the package:
import FileName from './FileName'; // Import the file
export { FileName } // Export the file to be used with the packagepackage.json
The package.json file needs to include new keys:
{ "name": "package-name", "version": "1.0.0", "private": false, "main": "dist/package-name.cjs.js", "style": "dist/package-name.css", "module": "dist/package-name.esm.js", "exports": { ".": { "import": "./dist/package-name.esm.js", "require": "./dist/package-name.cjs.js" } }, "files": [ "dist", "README.md" ], "author": "Author Name", "license": "MIT", "description": "Package description", "scripts": { "build": "vite build", "prepublishOnly": "npm run build" }, "dependencies": {}, "devDependencies": { "vite": "^3.0.0" }}Explanation of package.json fields
name: The package name.private: Iftrue, the package cannot be published on npm.version: The package version.main: The main file for CommonJS (CJS).module: The file containing the ES Module (ESM).style: The CSS file for the project.exports: Defines how the library should be imported.files: Specifies which files and folders to include in the published package.author: The package author.license: The package license (e.g., MIT).description: A brief description of the package.scripts: npm commands to run the build and prepare the package.
vite.config.js
The vite.config.js file needs to include the configurations for building the package:
export default defineConfig({ plugins: [react()], build: { lib: { entry: './src/index.js', name: 'library-name', fileName: (format) => `library-name.${format}.js`, formats: ['esm', 'cjs'] }, rollupOptions: { external: ['react', 'react-dom'], output: { globals: { react: 'React', 'react-dom': 'ReactDOM', } } } }})Running the Build
npm run buildThis command will generate the output files in the dist folder.
Login to NPM
Before publishing the package, log in to npm:
npm loginYou will be asked for your username, password and email. Alternatively, npm will provide a link in the browser.
Publishing the Package
npm publishThe package will be available for installation via:
npm install package-nameUpdating the Package
Modify the version in package.json and repeat the build and publish process:
npm version <major|minor|patch>npm publish