2

I am using a webpack template for Angular, provided by the angular starter seed at Angular Webpack Starter. This employs chunkhashing for production builds, (see webpack.prod.js).

I have modified the webpack configuration to generated a separate bundle for a webworker (see webpack.common.js). The filename is generated in the dist directory and named worker.[chunkhash].bundle.js.

Is there any way to determine the chunkhash for a bundle so that it can be correctly imported into Worker constructor, e.g.

let w: Worker = new Worker('worker' + chunkhash_variable + '.bundle.js')

Alternatively, is it better practice to

  1. Store javascript for web workers in the assets folder, let w: Worker = new Worker('assets/js/worker.js').

  2. Use the CopyWebPackPlugin to copy the web worker javascript from source folder to build folder.

Can anyone advise the best practice for referencing web workers?

webpack.common.js

module.exports = function (options) {
    ...
    const entry = {
      polyfills: './src/polyfills.browser.ts',
      main:      './src/main.browser.ts',
      worker:    './src/app/documents/webworkers/documentupload.webworker.js'
    };
    ...
}

webpack.prod.js

module.exports = function (env) {

  ...

  return webpackMerge(commonConfig({env: ENV, metadata: METADATA}), {

    output: {
      path: helpers.root('dist'),
      filename: '[name].[chunkhash].bundle.js',
      sourceMapFilename: '[file].map',
      chunkFilename: '[name].[chunkhash].chunk.js'
    },

    module: {
      rules: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        }),
        include: [helpers.root('src', 'styles')]
      },

      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader!sass-loader'
        }),
        include: [helpers.root('src', 'styles')]
      },
      ]
   },

   plugins: [

    new SourceMapDevToolPlugin({
      filename: '[file].map[query]',
      moduleFilenameTemplate: '[resource-path]',
      fallbackModuleFilenameTemplate: '[resource-path]?[hash]',
      sourceRoot: 'webpack:///'
    }),

    ...
}
dcs3spp
  • 493
  • 1
  • 9
  • 23

1 Answers1

3

Try using webpack loaders.

npm install worker-loader --save-dev

in your modules folder, use

{test: /\.worker\.js$/, use: { loader: 'worker-loader' }}

Then run your webpack build. Webpack will craete a [hash].worker.js in your bundle file. If you run your app and monitor the network, you'll notice that your [hash].worker.js file is being served and cached.

You can now use web workers by importing it. Notice the worker-loader! The prefix is required to call the worker.js file.

import Worker from 'worker-loader!./worker.js'

const myWorker = new Worker();

myWorker.postMessage();

myWorker.onmessage = function(){...}