I'm following this example, and many other similar, to separate vendor bundle from main JS file. I've got a multi-entrypoint app. So I'm going to have N HTML files like following
[articles.html]
<script type="text/javascript" src="vendor.js" charset="utf-8"></script>
<script type="text/javascript" src="articles.js" charset="utf-8"></script>
[categories.html]
<script type="text/javascript" src="vendor.js" charset="utf-8"></script>
<script type="text/javascript" src="categories.js" charset="utf-8"></script>
and so on. I have got my own modules, as well. I would like my own modules' code not to be repeated into articles.js, categories.js, etc. But to be bundled or with vendor bundle or in a separate bundle. For example
[articles.html]
<script type="text/javascript" src="vendor.js" charset="utf-8"></script>
<script type="text/javascript" src="mySharedModules.js" charset="utf-8"></script>
<script type="text/javascript" src="articles.js" charset="utf-8"></script>
So, following what it appears to be the commonly accepted method to build vendor bundle, I patched the gulpfile into something like
const mymod = ['./src/js/mod1.js', './src/js/mod2.js'];
gulp.task('build:mymod', function() {
const b = browserify();
mymod .forEach(function(lib) {
b.require(lib);
});
b.bundle()
.pipe(source('mySharedModules.js'))
.pipe(buffer())
.pipe(gulp.dest('./dist/'));
});
It's been built without errors, but the source path I had to specify (I don't know other way to refer to a module of my own, since it's not a NPM module...) is built hard-coded:
...
},{"../mod1.js":"/src/js/mod1.js","jquery":"jquery"}],2:
[function(require,module,exports){
var l = require("../mod1.js");
...
Of course the path "/src/js/mod1.js" doesn't make sense in "dist" directory. In fact I get an error: Cannot find module "/src/js/mod1.js".
Which is the correct way to bundle my own shared JS modules, either bundled with vendor's modules or separately?
Thank you
Your problem may lie in the usage of b.require
. Try passing an expose
option with your required files.
https://github.com/substack/node-browserify#brequirefile-opts
const mymod = [
{file: './src/js/mod1.js', expose: 'mod1'},
{file: './src/js/mod2.js', expose: 'mod2'}
];
gulp.task('build:mymod', function() {
const b = browserify();
b.require(mymod); // pass array of files w/ 'expose' property
b.bundle()
.pipe(source('mySharedModules.js'))
.pipe(buffer())
.pipe(gulp.dest('./dist/'));
});
According to the docs, require('mod1')
and require('mod2')
should now be enabled outside of the mySharedModules.js
bundle.