1

I'm currently migrating the whole code of a NodeJS application from ES5 to ES6/7.

I'm having trouble when it comes to imports :

First, I understood that making an import directly call the file. For example :

import moduleTest from './moduleTest';

This code will go into moduleTest.js and execute it.

So, the real question is about this code :

import mongoose from 'mongoose';
import autopopulate from 'mongoose-autopopulate';
import dp from 'mongoose-deep-populate';

import { someUtils } from '../utils';

const types = mongoose.Schema.Types;
const deepPopulate = dp(mongoose);

export default () => {
    // DOES SOMETHING USING types AND deepPopulate
    return someThing;
};

export const anotherModule = () => {
  // ALSO USE types and deepPopulate
};

Is this a good practice to have types and deepPopulate declared outside of the two exports ? Or should I declare them in each export ?

The reason of this question is that I'm having a conflict due to this practice (to simplify, let's say that dp(mongoose) will call something that is not declared yet)

5
  • 1
    I only see one module. The whole file is the module. export default ... and export const anotherModule ... are not modules, they are exports. It's completely fine to have module level variables shared by multiple functions in the module. I don't think we can help with your specific problem if you don't tell us what it is. Commented Oct 30, 2017 at 18:16
  • Not sure what you mean by "declared outside of the two modules"?
    – Bergi
    Commented Oct 31, 2017 at 9:07
  • I meant outside of the two exports, which mean that if I import this file, everything outside these two exports will be executed, which is a problem to me
    – GaldanM
    Commented Oct 31, 2017 at 9:21
  • And what exactly is that actual problem?
    – Bergi
    Commented Oct 31, 2017 at 9:33
  • Well, the problem is that the file I'm executing with Node is building a Mongo schema through it's code and using it later. Unfortunately, an import in this file (the code above) is using a schema that's not yet available (since the code from the main file hasn't done it's job ye) so I get an error telling me that the schema is not found.
    – GaldanM
    Commented Oct 31, 2017 at 9:45

1 Answer 1

0

You can only have one 'default' export to a module, or you can have multiple 'named' exports per module. Take a look at the following for a good description of handling exports in ES6: ECMAScript 6 Modules: The Final Syntax

1
  • Thanks for the link, I just went through it and it's really helpful! After a good thinking, I think that I will declare types and deepPopulate inside each export because I will have conflict if I let them be on top because they will be executed when this file will be imported. This is pretty disturbing to have these duplicate code, but so be it!
    – GaldanM
    Commented Oct 31, 2017 at 9:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.