Can't import a module

Hi
Here in the documentation there is an example of importing a module

// In a server-only file, for example /imports/server/mmr.js
export const MMR = {
  updateWithSecretAlgorithm(userId) {
    // your secret code here
  }
}
// In a file loaded on client and server
Meteor.users.methods.updateMMR = new ValidatedMethod({
  name: 'Meteor.users.methods.updateMMR',
  validate: null,
  run() {
    if (this.isSimulation) {
      // Simulation code for the client (optional)
    } else {
      const { MMR } = require('/imports/server/mmr.js');
      MMR.updateWithSecretAlgorithm(this.userId);
    }
  }
});

I can’t import a server module in lib folder. So how can I implement this example.
What I want is to have a method that runs on the client but execute part of its code on the server side (API calls)

in imports > server > apicalls.js

export const apicall = function () {}

in shared > methods.js

import {apicall} from "../imports/server/apicalls.js";

I get error

Uncaught Error: Cannot find module ‘…/imports/server/apicalls.js’

The reason the example in the docs works is because the require is inside in if block:

    if (this.isSimulation) {
      // Simulation code for the client (optional)
    } else {
      const { MMR } = require('/imports/server/mmr.js');
      MMR.updateWithSecretAlgorithm(this.userId);
    }

Meaning that it doesn’t run on the client and doesn’t throw the error trying to import a server-only module.

If you want to make a client-server call, you should be using a Method (like the example from the docs)

2 Likes