Angular library: Module not found error
Making a quick note of this, because figuring it out took me far too long…
This project is an Angular app and Angular library in one project. The app consumes the library directly, not via npm.
The app uses the paths
in tsconfig to configure importing of the lib:
// root tsconfig.json
{
"compilerOptions": {
...
"paths": {
"@mycompany/my-library": ["dist/my-library"],
"@mycompany/my-library/*": ["dist/my-library/*"]
}
}
}
This configuration works for ng serve
but fails for ng build --prod
with the following error:
ERROR in ./dist/my-library/my-library.ngfactory.js
Module not found: Error: Can't resolve 'my-library' in '/Users/tanya.gray/Projects/my-project/dist/my-library'
Thanks to a teeny tiny comment on a GitHub issue, I realised the cause.
The error occurred because the library name I used for “paths” in the root tsconfig did not match the “name” in the library’s package.json file. My paths included the scope prefix, while the library name did not.
I updated the package.json in the library so that the package name was the same as the one used in the root tsconfig:
// my-library package.json
{
"name": "my-library",
...
}
Changed to:
// my-library package.json
{
"name": "@mycompany/my-library",
...
}
After rebuilding the library, then rebuilding the app, the error was resolved.