justinlin
justinlin

Reputation: 141

How to change module.exports to import and export?

module.exports = function (idx) {
   this.camera = idx;
};

module.exports.CONFIG = function () {
  return Promise.resolve([]);
 };
module.exports.CONFIG.FLOOR = function () {
  return Promise.resolve([]);
}

I have a file that contains code like above. I require this file and console.log it. It only shows

function (idx) {
   this.camera = idx;
}

Why other attributes are hidden?

And if I delete first module.exports paragraph and console.log it, it shows an anonymous function(or default function ?) in CONFIG.

{ CONFIG:
  { [Function]
    FLOOR: [FUNCTION]
   }
}

I am wondering how to change it to import/export type instead of module.exports/require?

Thanks!

Upvotes: 1

Views: 2236

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

It looks like you have both named exports and a default export. When exporting, that would look something like:

// Default export:
export default function (idx) {
  this.camera = idx;
};
function CONFIG() {
  return Promise.resolve([]);
}
CONFIG.FLOOR = function () {
  return Promise.resolve([]);
}
// Named export:
export CONFIG;

Then, when importing them, you need to both import the default and the named:

import idxFn, { CONFIG } from '../foo';
      ^^^^^ default import
               ^^^^^^ named import

You'll then be able to access FLOOR by referencing CONFIG.FLOOR.

But, note that having a function which is a property of another function is really weird. You might consider exporting FLOOR as another named export instead, just like CONFIG:

// Default export:
export default function (idx) {
  this.camera = idx;
};
// Named exports:
export function CONFIG() {
  return Promise.resolve([]);
}
export function FLOOR () {
  return Promise.resolve([]);
}

Upvotes: 3

Related Questions