brfs icon indicating copy to clipboard operation
brfs copied to clipboard

Support dynamic require

Open sindresorhus opened this issue 10 years ago • 7 comments

Many modules uses require to dynamically load JSON files.

Example:

require('./path/' + name + '.json');

sindresorhus avatar Sep 11 '13 09:09 sindresorhus

This is pretty tricky but might be possible in some cases where name is statically resolvable. I think a static resolver module would be the best way to implement this.

ghost avatar Sep 11 '13 15:09 ghost

Another usecase (from cheerio):

var api = ['attributes', 'traversing', 'manipulation'];

api.forEach(function(mod) {
  _.extend(Cheerio.prototype, require('./api/' + mod));
});

Related ticket

Probably more of a browsersify core issue, but it does seem slightly related.

sindresorhus avatar Sep 11 '13 19:09 sindresorhus

The sledge hammer approach taken by nodejitsu/require-analyzer is to first check if all requires can be resolved statically, and if they can't, fire up a new node instance, monkey-patch Module#require and track everything that's required.

While this would certainly work for browserify, it might complicate the development process, as the compilation thread in the background might run into an infinite loop and block the system.

browserify should at least add support for statically resolving variables, plus some of the array extras. Especially map is interesting here, as I can imagine using ES6 destructuring expressions to require multiple modules at once will become a common pattern:

let [fs, path] = ["fs", "path"].map(require)

fb55 avatar Sep 11 '13 21:09 fb55

I have this use case

[ 'a.js', 'b.js' ].forEach(js => {
  injectJS(fs.readFileSync(js));
});

leesei avatar Apr 29 '16 19:04 leesei

I had this issue too, but as said before, couldn't achieve this with brfs. What I did was a simply fetch request. Would it be possible to replace

fs.readFile('posts/' + post + '.md', function (err, content) {
  // process file
})

with

fetch('posts/' + post + '.md')
   .then(response => response.text())
   .then(content => {
     // process file
   })

So it would dynamically load files with ajax?

YerkoPalma avatar Nov 24 '17 16:11 YerkoPalma

@YerkoPalma even better now:

var content = (await fetch(`posts/${post}.md`)).text()

dy avatar Oct 26 '18 13:10 dy

@dy fetch()'s return value doesn't have a .text() method, so with async/await you have to do something like

var resp = await fetch(`posts/${post}.md`)
var content = await resp.text()

goto-bus-stop avatar Oct 26 '18 13:10 goto-bus-stop