Public
Authored by Grant Hames-Morgan 🌺

Angular webpack build configuration

Normally I have a Node server host both the frontend and backend of a project via webpack-dev-middleware. Allows for tighter hot reloading. When porting to Angular (v8.0.0) I wanted to do ahead of time (AOT) compilation, but it seemed building outside of their NgCLI is unsupported. There's no eject. There's are a few notes about using @ngtools/webpack, and I got very close based off this guide here: https://angular-guru.com/blog/angular-webpack

Eventually skipped it and decided to use NgCLI since it's what the team uses - they'd make no sense of the complexity of this config. I don't even want to touch it. Further, NgCLI actually does an unbelievable job bundling in production. Minifying to around 196kB total, down from a 3MB hello world application.

This snippet is here in case I need to pick up the webpack integration again for Angular. Though, I've learned I never want to use Angular for a project outside work...

Here's how to tell Express/Koa/Node to use WDM and HMR.

import { Configuration } from 'webpack';
import webpackConfig from '../webpack.config';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

...

webpackConfig.mode = process.env.NODE_ENV as Configuration['mode'];
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
  publicPath: '/',
  index: 'index.html',
  // Less verbose
  logLevel: 'warn',
}));
app.use(webpackHotMiddleware(compiler, {
  heartbeat: 10 * 1000,
  log: console.log,
  path: '/__webpack_hmr',
}));

...

The snippet has the webpack configuration.

Edited
webpack.config.ts 3.9 KB
  • Re: // Can't really trust __dirname because TS -> JS will move files around...

    Is because the config had the option of being run by ts-node or first being compiled into dist/ via tsc and then run by the usual node from inside dist/.

    {
      "start": "ts-node-dev -r esm --transpile-only server/server.ts",
      "start-compiled": "node -r esm dist/server/server.js",
      "build-server": "tsc --build tsconfig.json",
      "build-client": "node -r esm -r ts-node/register ./node_modules/webpack/bin/webpack.js --config webpack.config.ts"
    }

    Specify --mode for webpack as appropriate.

    Edited by Grant Hames-Morgan
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment