Shimming module in webpack

900 Views Asked by At

I'm building a typescript project with a module, tiny-worker, as a dependency of a dependency (not a direct dependency). tiny-worker uses node's child_process which doesn't exist in the browser.

I followed Webpack's shimming guide and added the following to my webpack config:

plugins: [
    new webpack.ProvidePlugin({
      'tiny-worker': 'Worker'
    })
  ],

However, when I try to run webpack it still complains about child_process in tiny-worker

ERROR in ./node_modules/tiny-worker/lib/index.js
 @ ./node_modules/tiny-worker/lib/index.js 8:11-35
 @ ./node_modules/pollenium-anemone/node/src/classes/MissiveGenerator.js
 @ ./node_modules/pollenium-anemone/node/main.js
 @ ./src/globals/anemoneClient.ts
 @ ./src/classes/BopManager.ts
 @ ./src/classes/Market.tsx
 @ ./src/globals/markets.ts
 @ ./src/app.tsx
 @ ./src/index.ts
 @ multi @babel/polyfill ./src/index.ts

How can i get Webpack to use window.Worker instead of import Worker from 'tiny-worker'

1

There are 1 best solutions below

2
Akhil F On

Solved this using module-replace-webpack-plugin

https://www.npmjs.com/package/module-replace-webpack-plugin

plugins: [
    new ModuleReplaceWebpackPlugin({
      modules: [{
        test: /^tiny-worker$/,
        replace: './shims/Worker.js'
      }]
    })
  ]

and created shims/Worker.js which simply re-exports window.Worker

export default window.Worker