2

Using Browserify, this works:

var b = require('path/file.js')

But this one not:

var a = 'file'
var b = require('path/' + a + '.js')

Any ideas why?

kvdmolen
  • 183
  • 2
  • 13
  • possible duplicate of [Compiling dynamically required modules with Browserify](http://stackoverflow.com/questions/21642398/compiling-dynamically-required-modules-with-browserify) – Pete TNT Sep 11 '15 at 08:56
  • Similar, though for me a bulk-require is not the solution since actually I have to use it as `var b = require('path/' + a + '.js')` – kvdmolen Sep 11 '15 at 09:38

1 Answers1

2

Because Browserify parses the source code and not execute it to figure out dependencies. The second case would required the execution of code to find the dependency path. In this case it is a simple variable which is constant but it could be any other value which is computed based on some query from some API etc.

Ankur
  • 33,367
  • 2
  • 46
  • 72
  • Is there any way around this? Or switch to Webpack/RequireJS orso? – kvdmolen Sep 11 '15 at 08:51
  • I guess you will have to use client side module systems like requireJS etc if you want dynamic module loading. But remember that you wont be able to use any js unification technique where you end up with a single JS file with all modules if you use dynamic module names – Ankur Sep 11 '15 at 08:55
  • See this http://stackoverflow.com/questions/21642398/compiling-dynamically-required-modules-with-browserify for options for dynamic bundling – Pete TNT Sep 11 '15 at 08:56