Build an Angular2 Library with Webpack

I was trying to build an Angular2 library, but it actually took me a while to figure it out. I hope this post will help me or others in the future.

Here is the project, angular2-clipboard

It is written in Typescript. However, people want to have a build in plain old Javascript.

My first thought was pack it with Webpack.

But how to exclude something like Angular2 from this library ?

In Webpack, there is a option call externals

Here is code I used in my angular2-clipboard project

Webpack.config
1
2
3
4
5
6
7
8
9
10
externals: {
"clipboard": "clipboard",
'@angular/core': { root: ['ng', 'core'], commonjs: '@angular/core', commonjs2: '@angular/core', amd: '@angular/core' },
'rxjs/Rx': { root: 'Rx', commonjs: 'rxjs/Rx', commonjs2: 'rxjs/Rx', amd: 'rxjs/Rx' },
'rxjs/add/operator/let': {
root: ['Rx', 'Observable', 'prototype'],
commonjs: 'rxjs/add/operator/let',
commonjs2: 'rxjs/add/operator/let',
amd: 'rxjs/add/operator/let'
}

But it doesn't work. If you check the output js, you will find @angular/core module is like

1
2
3
4
5
function(module, exports) {
module.exports = undefined;
}

It turns out there are 2 settings in output section needs to set. library and libraryTarget

Here is the example,

Webpack.config
1
2
3
4
5
6
output: {
path: './',
filename: '[name].js',
library: 'ngII', // you can call it whatever you want.
libraryTarget: 'umd'
}

Ref 1: Webpack Series (Part 1): Some Configs Explained

Ref 2: NG Bootstrap

Ref 3: How to publish a library for Angular 2 on npm