BartB BartB - 1 month ago 32
Node.js Question

How to create a ready to publish to npm angular 2 library

I will be very specific and will divide my question into points.

1. What I want to achieve in overall:

Creating a ready to be published to npm angular 2 boilerplate library (latest version)

2. What is not working:

Both tutorials beneath, cited at stackoverflow earlier are not working properly in many aspects or are outdated or just not very clear. Also in the Internet there is more confusion than information about how to prepare a valid and working angular 2 library.

http://blog.angular-university.io/how-to-create-an-angular-2-library-and-how-to-consume-it-jspm-vs-webpack/

https://medium.com/@OCombe/how-to-publish-a-library-for-angular-2-on-npm-5f48cdabf435#.c3yuzcrgj

3. What I want to achieve in specific:

I would like to know the steps and summarize here what is essential for
creating the library in the latest angular 2 version from scratch. With code
examples. May it serve all stackoverflowers for the future as a
working boilerplate.

What I propose is to write down a shortest possible list what needs to be done in points, with code examples.

Answer

If I understand your question well, you want to create a component and publish it as a library.

1. Create the component

You need to create your foo.component.ts file and its html template. You'll prefer inline css (in styles attribute of @Component).

!!! Don't forget to set moduleId: module.id in @Component to link the template to your component using a relative path !!!

2. Compile the code (once you tested it, the testing part is implicit)

You need to compile your component using tsc and a tsconfig which should look like this:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "inlineSources": false,
    "declaration": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "stripInternal": true,
    "skipLibCheck": true
  },
  "files": [
    "index.ts",
    "typings/index.d.ts"
  ]
}

3. Publish to npm

First of all, create your .npmignore file, here is an example:

.idea

*.ts
!*.d.ts

/typings.json
/typings/
/node_modules/
/.gitignore
/.npmignore
/.travis.yml

/test
/karma.conf.js
/karma-test-shim.js

/rollup.config.js
/rollup-min.config.js

/systemjs.config.js

/tsconfig.json
/tsconfig-build.json

If you're not using a JetBrains IDE, remove .idea entry.

then set your publish configuration in package.json:

"publishConfig": {
    "registry": "https://registry.npmjs.org/"
}

Once everything is ready, you can npm publish.

Example

A good example of an external library for angular2 can be found here: https://github.com/noemi-salaun/ng2-logger/

It's not a component, but the whole publish config, bundling and testing logic is wel done.

Comments