Search code examples
typescriptbrowserifytsify

Mixing javascript and typescript in gulp browserify


I have nice gulp browserify workflows for javascript and now typescript. These combine the source files with modules and generates a single .js file for use in the browser.

However, having an older javascript project I now wanted to introduce new functionality using typescript - without converting everything to typescript.

Ideally I want browserify to detect and pre-compile ts and tsx, and pass the result along with js-files to babel before browserifying:

function compileBrowserify(file, folder, watch, typescript) {
    // cache and packageCache is required for watchify to perform, debug produces sourcemaps. })
    var bundlerRaw = browserify(file, { debug: true, cache: {}, packageCache: {}}) 
    var bundler = watch ? watchify(bundlerRaw) : bundlerRaw

    bundler = typescript ? bundler.plugin(tsify, { noImplicitAny: false,  jsx: 'react', moduleResolution: 'node', target: 'ES6'}) : bundler
    bundler.transform(babelify.configure({
        presets: ['react', 'es2015', 'stage-0'],
        }))

    var rebundle = function() {
        return bundler
            .bundle()
            .on('error', function(err) { console.error(err.toString()); this.emit('end'); })
            .on('end', function() { console.log('Done browserifying'); })
            .pipe(source("app/main.js"))
            .pipe(buffer())
            .pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(folder));
    }
    bundler.on('update', rebundle)
    return rebundle()
}

This setup actually compiles and works for the js-part, but my typescript file is not bundled. Is it possible to add typescript files to an existing javascript project in this fashion?

Note: I'm adding a React tsx file for the moment, but assume that the case would be the same for regular ts files.

Note: I have tried to manually "add()" the tsx file to the browserify bundle, without any high hopes or results.

Note: The tsx is compiled, atleast it fails the build on errors, it's just not put into the bundle.


Solution

  • Sorry, but the above code is actually working. I was missing the correct exports from the tsx file, and browserify/tsify must have found that there was nothing useful to output.

    Anyway, it's really cool that this setup works. It makes it very easy to continue building on javascript projects - using the strength of typescript.