Search code examples
reactjstypescriptnode-modulesnpm-publish

Unable to resolve published NPM module in project


I recently published a simple React module that I wrote in TypeScript. I tested my module by importing the local package into a project, and it worked flawlessly. However, now that I've published the module, whenever I try to import it into a project, I get the following error:

Failed to compile.

./src/...
Module not found: Can't resolve '<module>' in '.../src/...'

Package is listed in both package.json and package-lock.json, and the module shows up in node_modules. Additionally, VS Code doesn't throw any fits, so I'm not quite sure what could be the issue.


Solution

  • NPM, being the "Node Package Manager" interprets packages as node modules. in the documentation, it says it will try to load a folder by looking for a package.json file, and resolving the path in main relative to the folder it found.

    So when publishing a package with a build step, always make sure to build it before its published (there is a prepublish hook for this, in the scripts object in package.json).

    The other thing is to make sure that the package being published refers to the correct main, bin (if applicable), and module (if applicable) paths in the package.json file. if the source file is src/mylib.coffee and the built file is dist/mylib.js, the package.json must contain { "main": "dist/mylib.js" } in order that someone installing this module as a dependency into their node_modules folder would require the correct file.

    in short make sure "main" in package.json points to the right file!