Search code examples
javascriptnode.jsnpmnpm-publish

I am trying to export my npm package. How to do it properly?


I've created an npm package

class Person {
     constructor() {}
     sayHello() {console.log("Hello World!")}
}

module.exports = Person;

After doing npm i my-package it was added the lib to my project.

On my index.js I am doing the following:

const Person = require('my-package');

const david = new Person();

But I get this error: Error: Cannot find module '/Users/me/test/node_modules/my-package/app.js'. Please verify that the package.json has a valid "main" entry

It works fine when I require it like this:

const Person = require('./node_modules/my-package/person.js');

const david = new Person();

What am I doing wrong? How can I set my package to export Person using const Person = require('my-package');


Solution

  • the main in my package.json file pointed to app.js (default by npm).

    I had to change it to point to my actual main.

    {
      "name": "my-package",
      "version": "1.0.0",
      ...
    
      "main": "index.js", // <------ I changed it from app.js to my actual main
       
       ...
    }
    

    Thank you @evolutionxbox for your comment. It helped me a lot.