Skip to content

Instantly share code, notes, and snippets.

@RascalTwo
Last active February 2, 2023 00:07
Show Gist options
  • Save RascalTwo/499cd32b058edf34001e9c0b5ddefbf1 to your computer and use it in GitHub Desktop.
Save RascalTwo/499cd32b058edf34001e9c0b5ddefbf1 to your computer and use it in GitHub Desktop.
Webpack-ify Node.js Server

Quick instructions for Webpack-ifying backend Node.js code:

  • npm install --save-dev webpack-node-externals webpack webpack-cli nodemon
  • Ensure main is within package.json
  • Add *.dist.js to .gitignore
  • Create included webpack.config.js
  • Run npx webpack --watch in combination with npx nodemon MAIN.dist.js

To make things easier, additionally:

  • npm install --save-dev nodemon
  • Add node MAIN.js as the start script.
  • Add nodemon MAIN.dist.js as the dev script.
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const entry = './' + require('./package.json').main;
let outputFilename = path.basename(entry).replace(/(\.[^/.]+)$/, '.dist$1'); // Add .dist prefix to extension
module.exports = {
mode: process.env.NODE_ENV || 'development', // Run in development by default
entry, // Copy the entry point from package.json
target: 'node', // Tell webpack to compile for node
externals: [nodeExternals()], // Ignore all modules in node_modules folder
externalsPresets: {
node: true // Ignore built-in modules
},
resolve: {
extensions: ['.js'], // Allow imports that exclude .js extension
},
output: {
filename: outputFilename,
path: path.resolve(__dirname),
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment