How to load a 3rd .js file in a Angualr-cli TypeScript file

After completing the function that auto-detecte the run-time container, the following problem is how to load a 3rd JavaScript file in a Angular-cli TypeScript file and how to invoke functions in that file.
All the day I search the Internet and finally I made a solution:

// electron.service.ts
import { Injectable } from '@angular/core';
import { ipcRenderer } from 'electron';
import { sadd } from 'randy-assets/sadd';
declare let nw: any;
@Injectable()
export class ElectronService {
  ipcRenderer: typeof ipcRenderer;
  containerType: string;
  mylib: any;
  constructor() {
    // Conditional imports
    // console.log(sadd(1, 2));
    this.detectContainer();
  }
  private detectContainer() {
    if (this.isElectron()) {
      console.log('In Electron!');
      this.containerType = 'ELECTRON';
      this.ipcRenderer = window.require('electron').ipcRenderer;
      // this.mylib = window.require('electron').remote.require('./randy-assets/lib-oper');
    } else {
      try {
        console.log(nw);
        console.log('In nwjs!');
        this.containerType = 'NWJS';
      } catch (e) {
        console.log('In browser!');
        this.containerType = 'BROWSER';
      }
    }
    console.log('Container type:', this.containerType);
    this.add(1, 2);
  }

  public add(n1: number, n2: number) {
    console.log(sadd(1, 2));
    switch (this.containerType) {
      case 'ELECTRON':
        console.log('Into electron add');
        break;
      case 'NWJS':
        console.log('Into nwjs add');
        break;
      case 'BROWSER':
        console.log('Into browser add, cause it\'s in browser, cannot execurt this statement');
        break;
      default:
        console.log('Switch Error!');
    }
  }
  private isElectron = () => {
    return window && window.process && window.process.type;
  };
}

The main code is not the point, see the imports.

 import { sadd } from 'randy-assets/sadd';

In randy-asset folder, we have two files: sadd.js and sadd.d.ts, and their contents are:

// sadd.ts
export function sadd(n1: number, n2: number): number;

and

// sadd.js
let sadd = (n1, n2) => {
  return n1 + n2
};
module.exports = {
  sadd
};

All the references are listed below:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,168评论 0 10
  • 诵一篇《回答》 读两首《沁园春》 写下几行略显浅薄的文字 于风华正茂之年 以书生意气 指点江山 缀满天空的星斗 凝...
    四十二客星阅读 1,576评论 2 3
  • 作者:赵阿萌 原地址:http://zhuanlan.zhihu.com/whiteroom/19804178 在...
    了不起的顾惜朝呀阅读 2,994评论 0 1
  • 一. 水平居中 margin: 0 auto 当子元素 display: inline-block 时,父元素 t...
    McDu阅读 15,687评论 1 4

友情链接更多精彩内容