美文网首页我爱编程
How to load a 3rd .js file in a

How to load a 3rd .js file in a

作者: 环零弦 | 来源:发表于2018-02-28 16:41 被阅读0次

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:

相关文章

网友评论

    本文标题:How to load a 3rd .js file in a

    本文链接:https://www.haomeiwen.com/subject/kjhixftx.html