5
votes

For me, Webpack is a bundler for "web" since browsers don't have good support for js module system. Thus using Webpack we could still use "module" way to develop and pack them for browsers.

Webpack has a config option target

module.exports = {
  target: 'node'
};

using node webpack will compile for usage in a Node.js-like environment

But NodeJS already support CommonJS modules, why need Webpack to build something that runs in NodeJS environment?

Besides, if you want to compile your javascript, for example, using the ES module, you could just use babel to do so, using es module transform plugins or proper presets.

Why use Webpack, set the target to node and then use babel loader... instead of using babel directly?

I cannot think of the use case of using Webpack to bundle application running in node.

2
Webpack is sure a bundler but has support for many different use cases like parsing files, hashing parts and so on through plugins which is useful and readable.binariedMe
A good example is universal app that already uses Webpack to run in browser and uses its specific features (aliases, loaders, etc). In order to run it in Node it needs to be bundled with Webpack, too.Estus Flask

2 Answers

3
votes

One reason I can think of when to use webpack for node is when you have a node_modules package where it's not compiled yet (Still in ES6).

babel-node won't be able to help you bundle the node_modules packages that need to be transpiled along with the rest of your code

I had to go through this process.. ): This scenario is helpful in Yarn Workspaces where you want your server to depend on another package in your workspace. Where your server will re-update whenever you make changes in the other package with the help of webpack

How to include a few node_modules package in babel-node

0
votes

Having a single server.js output

  • instant deployable on a server
  • no worry about mismatching dependencies compared to your dev environment.