Home > Net >  How to create a Angular library NPM package, that will allow importing modules the way the Angular M
How to create a Angular library NPM package, that will allow importing modules the way the Angular M

Time:01-18

In Angular Material (AM) we can import single module from the @angular/material like this: import { MatButtonModule } from '@angular/material'

I would like to re-use this approach also for my library, but when my library is build index.ts re-export everything from public-api.ts. This means that all the modules from my library are imported in the target app as follows:

  • import { MyModule1 } from 'my-lib'
  • import { MyModule2 } from 'my-lib'

But instead I would like to have imports similar to AM, like this:

  • import { MyModule1 } from 'my-lib/my-module-1'
  • import { MyModule2 } from 'my-lib/my-module-2'

I wasn't able to find any guide / recommendation on how to do that and would appreciate some suggestion or maybe a blog with explaining how Angular team achieved it.

CodePudding user response:

Here's a solution

  1. Create a folder for your library and create an npm package.json file in the root of the folder.

  2. Install Angular CLI and create a new workspace for your library.

  3. Create a public_api.ts file that will contain all the exported modules from your library, such as components, services, directives, pipes, etc.

  4. Create an index.ts file that will import all the modules from public_api and export them to be imported by other projects using your library.

  5. Configure the angular-cli to build your library into an npm package using ng-packagr or rollupjs and configure it to compile all the files in the src folder into a single bundle file in the dist folder of your project

  6. Publish your library to npm using npm publish command

  7. Now you can import individual modules from your library in other projects just like you do with angular material!

CodePudding user response:

the approach taken by Material-UI requires some extra steps. Let's assume the project is called my-package.

my-package
  package.json
  src/
    index.js
  dist/
    index.js

After publishing the root of the project. when installed the project ends up in node_modules like so

node_modules
  my-package/
    package.json
    dist/
      index.js

Now on other project you will use the import

import myProject from "my-project";

which will work fine. But the subpaths like below needs small trick

import something from "my-project/something";

Trick: instead of publishing your project root with its dist folder, publish the dist folder using npm publish dist instead. so that after build it looks like

node_modules
  my-package/
    package.json
    dist/
      index.js
      something.js

Once published we get

node_modules
  my-project/
    package.json
    index.js
    something.js
  • Related