Search code examples
javascriptnode.jsecmascript-6module-export

Exporting multiple functions with module.exports in ES6


I'm building a node.js application and I'm trying to put all my mongodb logic in a seperate file. At this time this file only has one function to initialize the mongodb connection. I want to export all the functions from this file using module.exports.

My mongo file looks as follows:

import { connect } from "mongoose";

const run = async (db: string): Promise<void> => {
  await connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
};

module.exports = {
  run
};

I want to use this run function in index.ts and im trying to import it as an ES6 module but I can't get it working with the above code.

How I'm importing:

index.ts:

import * as mongo from "./mongo";

Trying to call my run method:

mongo.run('dburl');

This throws following error: 'property run does not exist'

Now I have found a solution to this problem by adding an extra export before my run declaration:

export const run = async (db: string): Promise<void> => {...}

I don't understand why I have to do this as I'm already exporting this function inside module.exports, am I importing it wrong in my index file or is there a better way of doing this?


Solution

  • MDN: JavaScript Modules

    There are different types of modules in JS.

    ES6 Modules use the export keyword. You can import all the exports like this import * as ... from "..." or import individual exports via import { ... } from "..."

    CommonJS modules use modules.exports which is equivalent to export default in ES6 modules. These you can import like this import ... from "...".

    So when you use modules.exports you would either have to change your import to:

    const mongo = require('./mongo');

    Or you could change your export to:

    export { run }