Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Stencil components and Vue

2018-09-14

Recently I build some components with Stencil for an Angular project. Unsurprisingly the created components also work well with Vue. There are two steps necessary. Here is the workflow:

First Step: Create your Stencil component

At first create a directory and install Stencils dependencies.

mkdir stencil-components
cd stencil-components
npm init -y
npm install @stencil/core -S
npm install @stencil/utils -D

Now create your component in Stencil. That is well documented here. Name it my-first-component.tsx

import {Component, Prop} from '@stencil/core';

@Component({
    tag: 'my-first-component',
    styleUrl: 'my-first-component.scss'
})
export class MyFirstComponent {

    // Indicate that name should be a public property on the component
    @Prop() name: string;

    render() {
        return (
            <p>
                My name is {this.name}
            </p>
        );
    }
}

Setup the build system for stencil with a file called stencil.config.js:

exports.config = {
    namespace: 'stencil-components',
    generateDistribution: true,
    generateWWW: false,
    bundles: [{components: ['my-first-component']}]
};

And a package.json:

{
  "name": "@vweber/stencil-components",
  "version": "1.0.0",
  "description": "",
  "main": "dist/stencil-components.js",
  "browser": "dist/stencil-components.js",
  "types": "dist/types/components.d.ts",
  "collection": "dist/collection/collection-manifest.json",
  "files": [
    "dist/"
  ],
  "scripts": {
    "build": "stencil build",
    "start": "serve .",
    "prepublish": "npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@stencil/core": "^0.4.2"
  },
  "devDependencies": {
    "@stencil/utils": "0.0.4",
    "serve": "^6.4.9"
  }
}

Update

As JoshuaTS stated, you have a little helper in your toolbox doing a lot of the above work for you:

npm init stencil

Now you are able to publish that component:

npm publish --access=public

Second step: Include the component in vue

Before you are able to consume your component in Vue you have to include the dependencies in your package.json. Don’t forget to import the component in the main.js of your app.

Now it’s easy to use your Stencil component in the template:


<my-first-component v-bind:name="Alwin"/>

Happy coding!