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.

4
  • Something like a shared library ? Commented Oct 25, 2018 at 13:54
  • @ibenjelloun yeah right it should work in angular and javascript. Commented Oct 25, 2018 at 13:57
  • stackoverflow.com/questions/52418149/… Commented Oct 25, 2018 at 14:01
  • @SureshKumarAriya will same code work in NodeJS also? Commented Oct 29, 2018 at 4:17

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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..
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); }
}

2 Comments

I have thousands of functions in .js file so each time I'll have to do this. Or I can access it using *?
Also if each of your js file returns an object, then you can directly have that as " declare var objectName : any

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.