Search code examples
typescriptgulpbrowserifyweb-worker

Why does browserify step in gulp build process compile my web worker typescript code?


I am trying to set up a web worker in a React/Typescript project that uses Gulp with Browserify for build. This is turning out to be quite a hard thing to do. The problem I have at the moment is that the typescript compilation step for the main app is attempting to include the web worker code. That fails, because web-worker typescript needs different types to the rest of the code - no DOM types are allowed. But I cannot see how the code comes to be included in the compile at all. As far as my understanding of browserify goes, it looks at the dependencies specified in the root file, and builds a dependency tree from there. That tree should never reference the web worker file and its code, so what is going on?

Gulp code:

const compileMainScript = (done) => {
  log('Compiling script for my-app');
  return browserify({
    basedir: '.',
    debug: mode === 'dev',
    entries: ['src/my-app/my-app.tsx'],
    cache: {},
    packageCache: {},
  })
    .plugin(tsify)
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('*path-to-destination-folder*'))
    .on('error', err => {
      console.error(err.toString());
      done(err);
    });
};

The (simplified) directory structure is something like:

-src
  -workers
    my-worker.ts
  -my-app
    my-app.tsx

Thus you can see that the app being built (my-app) and the web worker are in paths at the same level - it's not even like the web worker code is inside the my-app folder. How does browserify even come to see it? Note that there are no references to my-worker anywhere in my-app. I can change the folder or file name of the worker arbitrarily and the same problem occurs.


Solution

  • I'm not familiar with browserify + tsify build config. But I do know that TS compiler by design takes whole project into consideration when compiling, unlike babel's single-file strategy.

    So it sounds to me your problem is raised because the ts compiler takes the worker file as part of the project. You need to exclude it from your project.

    You can experiment with the "exclude" field in tsconfig.json, or try the following according to the tsify docs:

    browserify({ ... }).plugin(tsify, { files: [] })
    

    tsify supports overriding the files, exclude and include options. In particular, if "files": [] is specified, only the Browserify entry points (and their dependencies) are passed to TypeScript for compilation.