Search code examples
node.jsangularnpmnpm-linkng-packagr

How to develop two angular modules locally where module A imports module B


When developing two local projects in angularjs(where one imports the other) I would simply run "npm link" in module B's folder and then run "npm link module-B" in my main module's folder and whenever I changed a file in module B I would see it directly in my browser serving module A.

But it doesn't seem to be as easy with angular(4).

I use ng-packagr to generate a dist folder.
I run npm link inside the dist folder.
I run npm link module-B in my main module's folder.
I then run ng serve --preserve-symlinks.

So far so good, it can understand the Components of module B. But if I try to change something in module B, rerun ng-packagr, my main module's "ng serve" fails to compile, I have to stop and start the ng serve.

I think ng-packagr first removes the dist folder and this triggers a rebuild in ng serve which fails and doesn't notice the newly created files that came after the deletion of the dist folder.

Do we have to use ng-packagr or is there some other way of doing multi-project-local-development.

Update:

If we comment out this section in ng-packagr.js it doesnt delete the folder and the browser updates whenever a file is changed and ngpackagr is run:

return Promise.all([ /*rimraf_1.rimraf(p.dest),*/ rimraf_1.rimraf(p.workingDirectory) ]);

But running ng-packagr takes some time depending on how big the library is. Since it builds the whole thing and not just files that are changed.


Solution

  • Ok I think I got it working. This solution feel much more straight forward and does not make use of ng-packagr. What I did was:

    • In module B I moved all my @angular-dependencies from dependencies to peerDependencies.
    • Added index.ts to root folder of module B containing:
      export * from "./src/.../panel.module"
    • Run "npm link" from module B's root folder
    • Run "npm link module-B" from module A's root folder
    • Run ng serve --preserve-symlinks

    The index.ts file does so that the import stays the same whether you take the module from an npm repository or developing locally:
    import {moduleB} from "module-b";

    I think this solution only works for Components that are meant to only be run in a "parent container", like a Project using the Component. If moduleB would have, lets say a demo-module/page, I think one would have to break it apart in two steps, first the demo module as a separate npm-project and the Component-module in a Child-npm-Project.