Alina
Alina

Reputation: 81

Reuse Angular 2 module in other app without publishing to npm?

Say you have two different Angular 2 apps and both of them need to make use of the same component.

I created the common component, made a library following this tutorial http://blog.angular-university.io/how-to-create-an-angular-2-library-and-how-to-consume-it-jspm-vs-webpack/, but npm will make my code public and I will have to pay to make it private.

So, the questions are:

  1. How should I create components the can be available for the work team?
  2. Is it necessary to publish to npm or can I just push my code to private github repo? And if so, how should I do that and what would be the process to reuse the code in an app?

Thanks in advance.

Upvotes: 8

Views: 2729

Answers (2)

Fateh Mohamed
Fateh Mohamed

Reputation: 21397

I suggest that you use NX for that, it's clean easy for sharing code between applications

  • create an NX workspace

    npx --ignore-existing create-nx-workspace MY_WORK_SPACE
    

you can now create multiplr application inside that workspace, they can be Angular apps or React App or a mix between them

   ng add @nrwl/angular --defaults
   ng g @nrwl/angular:application app1 // generate first app
   ng g @nrwl/angular:application app2 //generate second app

they are visible under apps directory

enter image description here

so now you have your apps, you can share code between apps through generating Libraries

 ng g @nrwl/angular:lib ui // ui is the name of your library

it's now avaible under libs directory

enter image description here

you can now work on your library by generating components and services:

ng g component sharedComponent --project=ui --export

Finally you can use your library in your apps (app1 and app2) by importing your UiModule

import { UiModule } from '@MY_WORK_SPACE/ui'; // @nameOfYourCreatedWorkspace/nameOfLibrary

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, UiModule], // import here
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

and Voila!

Upvotes: 0

jornare
jornare

Reputation: 2893

package.json allows you to reference packages downloaded from a git repository, and this could be the one you use internally. See NPM documentation

Example of formats:

git+ssh://git@github.com:npm/npm.git#v1.0.27
git+ssh://git@github.com:npm/npm#semver:^5.0
git+https://isaacs@github.com/npm/npm.git
git://github.com/npm/npm.git#v1.0.27

So this would in your package.json give something like:

"dependencies": {
   "privatepackage":"git://localgitserver/git/privatepackage.git"
}

Upvotes: 1

Related Questions