Skip to content

Instantly share code, notes, and snippets.

@yamadapc
Last active May 24, 2019 06:55
Show Gist options
  • Save yamadapc/9976164 to your computer and use it in GitHub Desktop.
Save yamadapc/9976164 to your computer and use it in GitHub Desktop.
browserify dynamic require
'use strict';
module.exports = 'a.js';
'use strict';
module.exports = 'b.js';
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="browser.js"></script>
</body>
</html>
// build with `browserify -o browser.js main.js`
require('./a'); // if this could be automated, or especified in another manner it'd be great.
require('./b'); // (this is the brick wall, as of today)
var modules = ['a', 'b'];
var mds = {};
modules.forEach(function(moduleName) {
mds[moduleName] = require('./' + moduleName);
});
console.log(mds.a, mds.b); // => "a.js b.js"
@emahuni
Copy link

emahuni commented May 24, 2019

The problem with your guest is that you're actually doing a require of the modules on the first static requires. Thing is, the program may never use some or all of the required modules in real life scenario. That dummy function prevents that and only makes the code actually do the require of the module when needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment