Moving import statements closer to where they are actually needed

A lot of us are looking forward to dynamic imports in Meteor 1.5 as described in Ben Newman demos Meteor 1.5

So I’ve been moving a lot of my import statements closer to where they are actually needed, including into conditional code (if and switch blocks).

However I have found that having an import statement in a switch case

const function1 = ([param]) => {
  switch (param) {
    case "A":

      break;
    case "B":
      import { x } from "../../group1/server/methods.js"
      
      break;
  }
}

produces an eslint related error in Visual Studio Code:

Cannot read property ‘indexOf’ of undefined

If I move the import to above the switch, that error does not appear and eslint works as normal.

Is this a bug, and if so, which eslint related package exactly is responsible?

Note that Meteor still builds and the app still works if the import is left in the switch case. So the problem is just with an eslint package.

Would it be correct to say that almost nobody has started to write import statements in places other than the top of a file? I hope that it will become acceptable practice soon.

Actually, in my case it’s more like I never use switch statements for some reason! (Nothing bad about them, just don’t like how they look I guess)

Since technically using import somewhere other than the top level isn’t yet a standard in JavaScript, it’s possible that not all tools support that. A simple workaround is to instead use require:

const function1 = ([param]) => {
  switch (param) {
    case "A":

      break;
    case "B":
      const { x } = require("../../group1/server/methods.js");
      
      break;
  }
}

If you later switch to a dynamic import, you can easily do that along with using async/await, you don’t even need to deal with promises!

const function1 = async ([param]) => {
  switch (param) {
    case "A":

      break;
    case "B":
      const { x } = await import("../../group1/server/methods.js");
      
      break;
  }
}
2 Likes