I want to avoid cluttering up my distribution bundle with library files and use separate script tags for them in the HTML.
One way is like this...
m1.js
module.exports = "first module";
m2.js
module.exports = "second module";
cnd-m1.js
var m1 = "first module";
main.js
var m1 = this.m1 || require("./src/m1");
var m2 = require("./src/m2");
console.log(m1);
console.log(m2);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>browserify test</title>
</head>
<body>
<script type="text/javascript" src="src/cdn-m1.js"></script>
<script type="text/javascript" src="dist/bundle.js"></script>
</body>
</html>
Where cdn-m1.js could be a library for example.
The only way I could figure out to make it work is to put a short-circuit fallback in the require statement and --ignore the file in my build.
in package.json
"scripts": {
"build-ignore": "browserify ./main.js -i ./src/m1.js > ./dist/bundle.js",
"build": "browserify ./main.js > ./dist/bundle.js"
},
Using the build-ignore script, the m1 module was stubbed in the bundle making it much smaller (assuming its a 50k line library) and it falls back on the cdn-served version.
bundle.js
function e(t, n, r) {
function s(o, u) {
if(!n[o]) {
if(!t[o]) {
var a = typeof require == "function" && require;
if(!u && a)return a(o, !0);
if(i)return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {exports: {}};
t[o][0].call(l.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for(var o = 0; o < r.length; o++)s(r[o]);
return s
})({
1: [function(require, module, exports) {
// browserify creates a stub for "./src/m1"
}, {}],
2: [function(require, module, exports) {
var m1 = this.m1 || require("./src/m1");
var m2 = require("./src/m2");
console.log(m1);
console.log(m2);
}, {"./src/m1": 1, "./src/m2": 3}],
3: [function(require, module, exports) {
module.exports = "second module";
}, {}]
}, {}, [2]);
Is there a better way to achieve this?