I want to use gulp to build bundles of JavaScript files.
For example I have the following structure in my project:
- /vendor/vendor1/vendor1.js
- /vendor/vendor2/vendor2.js
- /js/includes/include1.js
- /js/includes/include2.js
- /js/bundle1.js
- /js/bundle2.js
There are vendor includes (1-2), local includes (3-4), and bundle files (5-6).
Vendor includes are just third-party JavaScript libraries installed with bower or composer. They can be CommonJS, AMD or just a plain-old jQuery plugins.
I want to specify dependencies inside of a bundle files like this:
/js/bundle1.js
(function() {
// Vendor includes.
include('vendor1');
include('vendor2');
// Local includes.
include('includes/include1.js');
include('includes/include2.js');
// Some code here.
})();
I want gulp to process this source file and create a final distribution file (bundle) ensuring that all dependencies (includes) are merged together in a single file. So I can include foo.js from my HTML and all dependencies will be available to it.
I want to have a clear and robust system to manage all dependencies inside of a project and build distribution files.
- How can I achieve this?
- What format should I use for my own scripts (AMD, CommonJS, other)?
- How do I specify dependencies in my source bundle files?
- How do I build distribution?
There is a gulp plugin for this:
https://www.npmjs.com/package/gulp-include
It should do what you want, except that in your bundle file instead of this:
You would have to write:
Your question is posed as if there's a single answer, but there isn't. The problem you're trying to solve is one that many people have solved in many different ways, and you've identified two of the major options: AMD and CommonJS. There are other ways, but given that you might be new to Javascript dependency management as well as gulp, I'd recommend going with something that's relatively straightforward (even though this subject is inherently not straightforward).
I think the easiest route for you might be:
The statement in gulp to run browserify as such might look something like:
That should give you a dist/bundle1Output.js file.