0

I have a javascript file named sum.js

var addNumber = function (a,b){
  return a + b;
}
exports.addNumber = addNumber;

I want to use same sum.js file's addNumber function in nodeJS and in Angular 5. How can I do it. Is there any ways to do it?

Your help will be highly appreciated.

Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51

3 Answers3

2

I am able to use it in NodeJS as

var sum = require('./sum.js');

But I was not able to use it in Angular, So I declared var require: any; on the top.

 declare var require: any;
 var sum = require('./sum.js');

I found this solution.

Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
0

You can create an npm package and use it in both:

https://medium.freecodecamp.org/how-to-make-a-beautiful-tiny-npm-package-and-publish-it-2881d4307f78

mruanova
  • 6,351
  • 6
  • 37
  • 55
  • 1
    During development it will be so tedious to build it and then use it in angular and node.. And not 100% if it'll at both end ie Node and angular.. – Saurabh Agrawal Oct 27 '18 at 00:08
0

You can give the reference of your js file in angular-cli.json like below

"scripts": [
    ....
    "./assets/js/sum.js"
],

and then in your .ts of angular you can directly use it by declaring it like

import * as sum from '../../........./sum.js' //ref of ur file

class xyz {
   let a = 0,b=1
   constructor() { sum.addNumber(a, b); }
}
djain4
  • 257
  • 2
  • 13
  • I have thousands of functions in `.js` file so each time I'll have to do this. Or I can access it using *? – Saurabh Agrawal Oct 25 '18 at 14:42
  • Also if each of your js file returns an object, then you can directly have that as " declare var objectName : any – djain4 Oct 25 '18 at 14:50