Same Function name in different directories


#1

Can I have same name functions in different folders and need to call at run time based on folder location and file ?


#2

This depends on what you mean by “call at run time based on folder location and file”. Do you mean the folder/file will be calculated dynamically somewhere? If you’re using Meteor ES2015 module support, you will be a bit limited by the fact that you can’t directly use dynamic import/require statements. Meteor does provide a work around for this though, which @benjamn outlines here. Basically as long as you’re importing/requiring a resource somewhere in your app with the full (non-dymaic) string literal, you can then reference it anywhere else in your app using a dynamic expression. Here’s a quick example:

/client/main.js


// These calls would happen somewhere, once
true || require('/imports/api/big_widgets/inventory_count.js');
true || require('/imports/api/small_widgets/inventory_count.js');

// Here are a few variables that can be used in future require statements
const directoryName = 'big_widgets'; // or 'small_widgets'
const fileName = 'inventory_count.js';

// You can now dynamically require the necesary files anywhere in your code
const inventoryCount =
  require(`/imports/api/${directoryName}/${fileName}`).inventoryCount;

console.log(`Inventory count: ${inventoryCount()}`);

/imports/api/big_widgets/widget_inventory.js

const inventoryCount = () => {
  console.log('Current inventory: 100');
};
export { inventoryCount };

/imports/api/small_widgets/widget_inventory.js

const inventoryCount = () => {
  console.log('Current inventory: 200');
};
export { inventoryCount };