Search code examples
javascriptgulpcommonjsgulp-4

How do I combine multiple CommonJS modules in a single JS file with Gulp.js?


I've used Gulp.js for a variety of different implementations, some of them were only about plain and simple minification of a single JavaScript source file, some of them were minification and copying of multiple files, while others were around using browserify and combining multiple files that depend on each other into a single minified file (optionally using Babel in between for transpilation, etc.).

However recently, I came across a unique (for me) scenario that I've never covered in any of my implementations: concatenating of multiple CommonJS module files into a single minified build file.

Consider the following example:

There's a common file named common.js with the following contents -

module.exports.add = (a, b) => a + b;
module.exports.subtract = (a, b) => a - b;
module.exports.foo = ...

And then there's another one (say index.js) using one of the functions that this file exposes -

const common = require('./common');

const sum = common.add(1, 2);

console.log(`The sum is ${sum}.`);

Is there a way to concatenate both files when I supply index.js as the entry? If it were for ES6 modules or even AMDs, I could have used browserify. Not that I tried it yet, but it sounds odd to be to use it for something that will never run in a browser.

Any help is appreciated.


Solution

  • After a lot of looking around and finding that no one has ever talked about doing something like that (as far as I could see), I conclude that concatenation of modules is not at all required.

    The concatenation will not serve any purpose (unlike on the web) and the target file or (files) will reside at the same local directory. The problem that I was trying to solve does not even exist in the first place. Hence, I decided to maintain one target file per source file.