Recently there’s been a lot of talk about the possibility of creating Web Components from a regular Angular component, but so far there are much fewer practical examples as to how to build one–in the sense of actually making the bundle that you could just add to an html and have a working custom element. It should be very easy in the future but for now we need to make do with some manual tinkering.

I do recommend you to read/watch linked presentations to learn about the specific possibilities of the technology (spoiler: they are endless 😉) but in the meantime let’s build a component for ourselves, with a focus on a minimal tooling thet we should need:

Note:

This is a from-scratch approach. I will follow this article with a setup based on Angular CLI project in separate post later this week.

Update: The CLI-based article is ready!

1. Initialize the project:

mkdir angular-element-demo

cd angular-element-demo

npm init -y demo

2. Install main dependencies:

Add the minimal amount of regular Angular family members:

(we need the latest, not yet officially released version 6 for this…

update: Angular 6 has been released, I’ve updated the article to reflect that)

… and friends:

npm i core-js rxjs zone.js

Now, for the elements we will need the Angular library and a polyfill:

npm i @angular/elements @webcomponents/custom-elements

3. Install dev dependencies

Let’s see: we will need Angular compiler, webpack , ngtools to combine them.. oh, and TypeScript:

npm i -D @angular/compiler-cli @ngtools/webpack webpack webpack-cli typescript@~2.7

Ok, enough installing for now. Now let’s write configurations.

4. Configure webpack

Again, as small configuration as possible–whatever is not necessary we skip, and we use whatever defaults webpack 4 provides:

(never heard of webpack? See its documentation for the details on the options set)

The minimal webpack.config.js that we need is:



module: {

rules: [{test: /\.ts$/, loader: '@ngtools/webpack'}]

},

resolve: {

extensions: ['.ts', '.js']

},

plugins: [

new NgCompilerPlugin({

tsConfigPath: './tsconfig.json',

mainPath: './src/index.ts'

})

],

mode: 'production',

stats: 'errors-only' // there are… few deprecation warnings that

}; // I expect to go away soon (Angular 6.0?)

// for now, let's not see them ;) module.exports = {: {[{test:, loader:}]},: {extensions: ['', '']},: [new NgCompilerPlugin({tsConfigPath: '',mainPath: '})],',: '' // there are… few deprecation warnings that}; // I expect to go away soon (Angular 6.0?)// for now, let's not see them ;)

5. Configure TypeScript

Our minimum viable tsconfig.json looks like this:

{

"compileOnSave": false,

"compilerOptions": {

"sourceMap": true,

"experimentalDecorators": true,

"emitDecoratorMetadata": true,

"moduleResolution": "node",

"target": "es2015",

"lib": ["es2017", "dom"]

}

}

That’s the end of our required setup! Wasn’t that bad, I hope?