Search code examples
javascriptgulpbrowserify

Use of gulp+browserify+babalify for ES6 code referenced from external javascript.


I have been working on a side project to our main project using es6 classes, import and export. The main code uses Angular 1 (i.e. AngularJS)

I have followed advice here and elsewhere on using browsify and babelify and have almost gotten it working but am stuck on what i hope is the last step. I cannot reference my library from the main code.

We use gulp so I need to fit it into that framework. I have come up with the following to create the library:

function cliCompile() {
    console.log('Compiling client-server...');
    return browserify({
        entries: 'cli/main.js',
        debug: true,
        require: './cli/main.js',
        transform: [babelify]})
        .bundle()
        .pipe(source('cli.js'))
        .pipe(gulp.dest('./app/compiled'));
}

The require generated by this is unique to my computer (full path) so I clearly need to use an alias. However, it appears aliasing doesn't work well with the above, or I don't know the correct format. Changing the requre line to

require: 'cli/main.js:CSMain" 

did not work as it treated the full thing quoted string as the filename/module.

Is there a way to rewrite this so it would work and have an alias I can refer to in the main angular code? Note that the line to reference the function I gave above is:

gulp.task('cli', cliCompile);

Solution

  • Aliasing does get around this. However it appears you cannot specify require options when you pass in require as part of the initial parameters.

    Instead call .require as follows:

    gulp.task('cli', cliCompile);
    ....
    function cliCompile() {
        console.log('Compiling client-server...');
    
        var b = browserify({
            entries: 'cli/main.js',
            debug: true,
            transform: [babelify]});
        b.require('./cli/main.js', {expose: 'cli'});
        return b.bundle()
            .pipe(source('cli.js'))
            .pipe(gulp.dest('./app/compiled'));
    }
    

    It is also possible to put the require in the list:

    return browserify({
            entries: 'cli/main.js',
            debug: true,
            transform: [babelify]})
                .require('./cli/main.js', {expose: 'cli'})
                .bundle()
                .pipe(source('cli.js'))
                .pipe(gulp.dest('./app/compiled'));