Reputation: 26537
Is there a Gulp plugin that allows me to include/concatenate JavaScript files together?
I'm trying to have a way in which I can "include" the contents of one JavaScript file in to others. By include, I mean having something like this:
// main.js
var a = 2;
///include an-include-file.import.js
// an-include-file.import.js
var b = 5;
"Compile" to something like this:
// compiled.js
var a = 2;
var b = 5;
Or, probably even better, something like this:
// compiled.js v2
var a = 2;
// wrapped in an anonymous, self-calling function to isolate scope
(function () {
var b = 5;
})();
I wrote a plugin myself to do just that, but I'd like to be able to use source maps. Implementing source maps myself is a bit more effort than I'd like to devote to this little project.
Now, I know I could use something like gulp-concat
, but there isn't an easy way to control their order. I'd have to modify the gulpfile every time I add a new file, and manually list them all out (or have lots of complicated patterns), which is a rather large pain.
I'd prefer something where I can use an import or include to precisely control where the file goes, and control it from the scripts themselves, not the build tool. Very similar to how LESS or something does it.
For LESS, what I do is I name suffix files with ".import.less" if I don't want them to generate their own standalone file, and then @import
them where I want them in other files. This makes it very easy to only generate the files I want, without simply creating one giant file.
Upvotes: 2
Views: 2038
Reputation: 26537
I ended up taking Mike's idea and using WebPack, in addition to Babel, to create ES6-style modules.
The basics look like this:
// math.js
export function sum (a, b) { return a + b; }
// main.js
import sum from "math";
console.log(sum(1, 2));
I use Gulp to handle my build process, which in a simplified manner looks like this:
var gulp = require('gulp'),
webpack = require('webpack-stream');
gulp.task('build', function () {
return gulp.src('main.js')
.pipe(webpack())
.pipe(gulp.dest('dist'));
});
My actual usage is much more complex, but that's the basic idea. I have to use babel-loader (with the ES2015 preset) in my webpack config to have it process the ES6 in to ES5, then WebPack puts them together in to one file.
Related reading:
Upvotes: 1