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 party js file
- Question about importing js file in typescript fashion
- Unable to load simple JS dependency into Angular 2/SystemJS project
- JavaScript Libraries In A TypeScript Application, Revisited
- Using and including a 3rd party JavaScript library in an Ionic 2 and Angular 2 [typescript] application
- How to use a third party js library in Angular 2 / Typescript application?
- Angular Cli Webpack, How to add or bundle external js files?
- Angular-cli Webpack 3rd part css files
- Loading 3rd party JS files to angular components files
- External JavaScript dependencies in Typescript and Angular 2
- Migrating From JavaScript
- Angular-Cli中引用第三方库
网友评论