0

This is really 2 questions in 1...

I have a Node backend with an Express middleware. On entry of the application, I am trying to load in express routes though an iteration. Previously this was done with requirejs but I am wanting to scrap all that out and use es6's import/export instead.

My current code (based on MEAN.js):

let initModulesServerPolicies = (app) => {
    forEach(config.files.server.policies, (policyPath) => {
        require(path.resolve(policyPath)).invokeRolesPolicies();
    });
};

I am trying to somehow get my code to be like this:

let initModulesServerPolicies = (app) => {
    forEach(config.files.server.policies, (policyPath) => {
        import path.resolve(policyPath).invokeRolesPolicies();
    });
};

Now, the main error that appears here is:

'import' and 'export' may only appear at the top level

I can continue to use requirejs but that will require me changing my es6 exports in those policy files back to module.exports.

I am using babel-polyfill to enable me to use es6 import/export on the server.

N.B.: config.files.server.policies will be an array of relative paths. This array size will frequently change as I will add/deduct modules from my app which is why it would be preferable not to import these explicitly and an iteration is much more preferable.

So my 2 questions are:

  1. Can import/export be encapsulated within a function (so not at top level)
  2. Can multiple files be imported via an iteration?

I expect these kind of hiccups when I am trying to use es6 code as it is not fully supported yet so if this cannot be done then I'll find another way.

wmash
  • 4,032
  • 3
  • 31
  • 69
  • 2
    No, `import` and `export` can only appear at the outermost nesting level of the module. They cannot even be inside a normal statement (like a `while` loop block). – Pointy Jan 14 '18 at 14:14
  • https://stackoverflow.com/questions/29329662/are-es6-module-imports-hoisted – Pointy Jan 14 '18 at 14:14

0 Answers0