简体   繁体   中英

dynamically load modules in Meteor node.js

I'm trying to load multiple modules on the fly via chokidar (watchdog) using Meteor 1.6 beta, however after doing extensive research on the matter I just can't seem to get it to work.

From what I gather require by design will not take in anything other than static strings, ie

require("test/string/here")

Since if I try:

var path = "test/string/here"
require(path)

I just get Error: Cannot find module, even though the strings are identical.

Now the thing is I'm uncertain how to go on about this, am I really forced to either use import or static strings when using meteor or is there some workaround this?

watchdog(cmddir, (dir) => {
match = "." + regex_cmd.exec(dir);

match = dir;

loader.emit("loadcommand", match)


});

loader.on('loadcommand', (file) => {
require(file);
});

There is something intrinsically weird in what you describe.

chokidar is used to watch actual files and folders.

But Meteor compiles and bundles your code, resulting in an app folder after build that is totally different from your project structure.

Although Meteor now supports dynamic imports, the mechanism is internal to Meteor and does not rely on your actual project files, but on Meteor built ones.

If you want to dynamically require files like in Node, including with dynamically generated module path, you should avoid import and require statements, which are automatically replaced by Meteor built-in import mechanism. Instead you would have to make up your own loading function, taking care of the fact that your app built folder is different from your project folder.

That may work for example if your server is watching files and/or folders in a static location, different from where your app will be running.

In the end, I feel this is a sort of XY problem: you have not described your objective in the first place, and the above issue is trying to solve a weird solution that does not seem to fit how Meteor works, hence which may not be the most appropriate solution for your implicit objective.

@Sashko does a great job of explaining Meteor's dynamic imports here . There are also docs

A dynamic import is a function that returns a promise instead of just importing statically at build time. Example:

import('./component').then((MyComponent) => {
  render(MyComponent);
});

The promise runs once the module has been loaded. If you try to load the module repeatedly then it only gets loaded once and is immediately available on subsequent requests.

afaict you can use a variable for the string to import.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM