Shared methods with module import

I wasn’t suggesting that the imports should not be done at the top whenever possible. And I can only see the need to do so when the imported code shouldn’t be available (maybe because it contains sensitive info and we only want the server to have it) or somehow is dependent on server side only technology (e.g., node FS). And this scenarios should arise mainly in shared (client and server) methods.

1 Like

Same issue here. Any news on a patch?

Patch for what? I don’t think there is anything to patch…

@hluz My common code imports some server-only functions.

if ( Meteor.isServer  ) {
  import { someFunction } from './someFile.js';
}

Meteor.methods({
   coolMethod( arg ) {
        //do some stuff in common code

        if ( Meteor.isServer ) {
           //execute private logic on the server
            someFunction(arg);
        }
   }
})

This used to work fine and all of sudden, it doesn’t. Hence patch. I assume it has to do with recent meteor upgrades but of course I’m not sure.

I think the correct way to do that is to put the import right next to where you call the function. With ES2015 scoping, you won’t be able to access that import outside and that’s correct.

You could also do:

let someFunction;
if (Meteor.isServer) {
  someFunction = require('./someFunction');
}

But doing the import right next to the code is probably better:

coolMethod(arg) {
  if (Meteor.isServer) {
    import someFunction from './someFunction';
    someFunction();
  }
}
2 Likes

Thanks for your quick and knowledgable reply, @sashko. I’ll make the change as you suggest.

Ran into this situation today. This works, but Is there a side-effect of having the import called many times over inline in the code like this?

ESM imports are only executed once, even when they appear many times. The JS engine (or in Meteor’s case the bundler) will just return an immutable reference to the already executed/executing module

One issue having it in an isServer block is that it will ship the imported code to the client, even if it’s not executed, as import statements are analysed statically by the bundler

2 Likes