2

Sorry if it's a duplicate but I can't find the solution to this issue.

In NodeJS, I need to export functions from one file to another. Here is what I tried in order to export (written in typescript):

/*** db.ts ***/

module.exports = {
    getDoc: (id:string):any =>  {
        return new Observable((observer:any) => {
            //Do something
        });
    },
    addDoc: (document:any):any =>  {
        return new Observable((observer:any) => {
            //Do something
        });
    },
}

And to import:

/*** main.ts ***/

import { getDoc, addDoc } from './db'

I want to keep this structure (being able to call each function - getDoc and addDoc - separately).

What am I doing wrong? The export doesn't seem to work.

1
  • What is value of 'module' in tsconfig.json Commented Mar 11, 2019 at 11:10

2 Answers 2

2

CommonJS exports aren't type-safe.

If they are used as named imports:

import { getDoc, addDoc } from './db'

They should be named exports as well:

export const getDoc = (id:string):any =>  {
    return new Observable((observer:any) => {
        //Do something
    });
};

export const addDoc = (document:any):any =>  {
    return new Observable((observer:any) => {
        //Do something
    });
};

Both export and import are supposed to be transpiled to CommonJS modules by TypeScript.

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

Comments

0

You can do like this:

module.exports = {
    firstMethod: function() {},
    secondMethod: function() {}
}

For calling your methods

var Methods = require('./db.js');
var method = Methods.firstMethod;

Comments

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.