How to include child processes in a webpack bundle?
Asked Answered
T

1

7

I have a Node app which uses the fork method to run a background process. The problem is that running the web pack configuration from the index doesn't bundle the background process's files resulting in an error when reaching the fork.

All the code uses Babel syntax along with some other goodies.

How do I tell webpack to also bundle the forked files?

Thanks in advance.

Terrilynterrine answered 14/7, 2017 at 16:18 Comment(7)
¯_(ツ)_/¯ If the code is in a source directory processed by your took chain should be fine. Without any details it's difficult to help.Eatmon
The webpack configuration targets index.js file and creates a bundle. Inside the index.js there is a child process like fork('daemon.js'). Both files use babel syntax and other features enabled by webpack. When the bundle is run and gets to execute the daemon.js file, it crashes because it's using non-transpiled syntax. How do I include the child process file to the bundle and run it in a different process?Terrilynterrine
Can you fork a method? It's likely trying to run the file directly using the relative path hence getting a non-transpiled version.Eatmon
Could you elaborate a little more on the solution please?Terrilynterrine
webpack doesn't seem to pack files referenced with child_process.fork()Crimson
@Terrilynterrine Did you find a solution for this?Graces
Seems like npmjs.com/package/webpack-fork-loader could do the trick here.Woodshed
W
2

Just stumbled into this problem myself, and thought I could mention that a quick fix is to add an additional entry in your webpack config for your child process (creates a separate bundle for your child process) and then make it use this bundle by some resolve-rules, or simply by string-replace-loader:

Some example webpack config:

module.exports = {
   // ...
   target: 'node',
   entry: {
     server: './server/server.js',
     daemon: './daemon.js'
   },
   output: {
     path: path.resolve(__dirname, '../serverdist'),
     filename: '[name].bundle.js'
   },
   module: {
     rules: [
       // ... your other existing rules for building the server code
       {
         test: /placeWhereYouAreCallingFork.js$/,
         loader: 'string-replace-loader',
         options: {
           search: 'daemon.js',
           replace: 'serverdist/daemon.bundle.js'
         }
       }
     ]
   }
   // Other webpack stuff...
};

This depends on the replace loader:

npm install --save-dev string-replace-loader

Maybe not the cleanest solution but it it worked for me, and I thougth it was quite simple.

Woodshed answered 25/5, 2020 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.