简体   繁体   中英

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!

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([]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM