Angular 6 – Cannot resolve crypto, fs, net, path, stream when building Angular

My current setup is Angular 6.1.0 with Angular Universal too but the project is based on an old (dead) project which was built on Angular 5. Upon building the server side assets, the builder throws a lot of error saying it cannot resolve crypto, or it cannot resolve fs, net, path, stream and some others. I just did a quick and dirty fix for now.

Update

The temporary solution is so annoying that I gave up and use the semi-permanent solution until Angular or Webpack applies some fix to this. See update at the bottom.

Overview

The error is thrown by the Webpack compiler script. Note that the missing modules are built-in node modules. The issue has been reported all over the Angular and Webpack Github issues but they seem to be confused on who needs to fix it, therefore, I just followed the quick and dirty fix I’ve found on one of the comments from Github.

Annoying Fix

The issue is that the Webpack config generated in this Angular project configured node to have the modules not loaded. Therefore, the fix is to modify the parameters to include these missing modules.

On every update of your node packages, edit this file:

node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js

Find the node key parameter and change the value from:

node: false

to:

node: { crypto: true, stream: true, fs: 'empty', net: 'empty' }

Note that if you upgrade your packages, most likely, you have to repeat this process again. You can build an automated script but I’ll do it manually for now.

Auto update Webpack config on every package install/update

The automated script to patch the Webpack config is based on these Github comments and Gist:

Angular CLI comment.

Github Gist where the script is based upon.

My tweak is simply to change the path since the comments above are a bit outdated.

Update package.json and add this line into the scripts section.

"scripts": {
  ...
  "postinstall": "node patch-webpack.js"
  ...
}

Then create the patch script patch-webpack.js

const fs = require('fs');
const f = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';

fs.readFile(f, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  let result = data.replace(/node: false/g, "node: {crypto: true, stream: true, fs: 'empty', net: 'empty'}");

  fs.writeFile(f, result, 'utf8', function (err) {
    if (err) return console.log(err);
  });
});

That’s it! This is way better!

This entry was posted in Angular and tagged , . Bookmark the permalink.

Related Posts

One Response to Angular 6 – Cannot resolve crypto, fs, net, path, stream when building Angular

  1. Therron says:

    Thank you – I have been searching the web for hours to resolve the above errors, your solution works like a charm.

Leave a Reply

Your email address will not be published. Required fields are marked *