javascriptweb-componentstenciljsstencil-component

How to use an external third party library in Stencil.js


I have a Stencil component and, as part of its business logic, I need to use an external Javascript file mylib.js. The Javascript file contains some business logic the Stencil component should use.

Here's my component:

import { Component, Element, Prop, h, Host } from '@stencil/core';
import moment from 'moment';
import mylib from 'src/js/mylib.js';

@Component({
  tag: 'dashboard-widget',
  styleUrl: 'dashboard-widget.css',
  shadow: false
})
export class DashboardWidget {

  @Element() el: HTMLElement;

  @Prop() canvas: HTMLElement;
  @Prop() channelName: string = "";
  @Prop() channelValue: string = "";
  @Prop() isBlinking: boolean = true;

  componentDidLoad() {
      console.log(mylib.test());
  }

  render() {
    return (
      <Host>
      <div class="card-content card-content-padding">
          <b>{this.channelName}</b>
          <h1 class="dashboard-card-value">{this.channelValue}</h1>
          <canvas class="dashboard-card-canvas"></canvas>
      </div>
      </Host>
    );
  }
}

I keep getting the error

TypeScript Cannot find module 'src/js/mylib.js'.

I tried:

import mylib from 'src/js/mylib.js';

import 'src/js/mylib.js';

import 'mylib' from 'src/js/mylib.js';

to no avail.

The mylib.js file is inside the js folder. The online documentation doesn't mention at all how to import external libraries. I've been successful importing moment.js but only because I installed it first by doing:

npm install moment

and then importing it inside the component by doing:

import moment from 'moment';

I also tried to "import" the external JS library by referencing it inside the index.html

<script src="assets/js/mylib.js"></script>

The library is available outside the component but not inside it


Solution

  • To import files that aren't installed by NPM you can use relative paths prefixed with ./ or ../:

    import mylib from '../../js/mylib.js';
    

    You can import everything that is exported from that JS file and even use named imports:

    mylib.js

    export function someFunction() {
      // some logic
    }
    

    dashboard-widget.tsx

    import { someFunction } from '../../js/mylib.js`;
    
    const result = someFunction();