Shikha thakur Shikha thakur - 2 months ago 14
Node.js Question

cannot find the name "module"

I am trying to run a simple typescript file where I am exporting a function named

sum
as shown below:

I am writing node script.

function sum(a:number):number{
return a;
}
module.exports.sum=sum;


I don't understand what I did wrong.

I wrote this simple script to understand the unit test case. I thought if this file is running properly then i will go and start basic test case using mocha and chai.

below is my test code:

"use strict"

// Import chai.
let chai = require('chai'),
path = require('path');

chai.should();

let SampleTest = require(path.join(__dirname, '..', 'sample.js'));

describe('Sampletesting', () => {
describe('function sum', function(){
it('should return number', function(){
sum(1).should.equal(1);
})
})
});

Answer

This peace of code is working fine for me;

let's say we have a module called math_utils.ts which exports a function named foo and an object called obj

 // typescript syntax for exporting 
 export function foo(a: number): number {
    // whatever
 }

 export const obj = { life: 42 }

 const _aPrivateObjectToTheModule = {}

 function _aPrivateFunctionToTheModule() {}

Now we define in the same folder another file, for example math_utils.spec.ts, which is going to import our module.

import { should } from 'chai'
import { foo } from './math_utils'
// now we are able to call math_utils.foo()

describe('foo', () => {
    it('should....', () => {
        foo(1).should.equal(1);
    })
})

Now, just for summary, in typescript you can import module members this way... or import the whole module as following:

import * as chai from 'chai'
import * as MathUtils from './math_utils' 
// now in an object called MathUtils we have every member defined with the keyword export
const should = chai.should

describe('foo', () => {
    it('should....', () => {
        MathUtils.foo(1).should.equal(1);
    })
})
describe('obj', ()=> {
   // ...
   MathUtils.obj
})
Comments