angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Webpack Config is stripping out Crypto

Open jmc265 opened this issue 10 years ago • 73 comments

  1. OS?
    Mac OSX El Capitan
  2. Versions. angular-cli: local (v1.0.0-beta.10, branch: webpack)
    node: 4.4.7
    os: darwin x64
  3. Repro steps. I've pulled down the Angular-cli project and am building it locally, so I am using the new webpack version. The project that I am building uses Crypto libraries (via a dependency of a dependency ...). When I was running ng build I was seeing the dependency built like this:
    /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict';

    var crypto = __webpack_require__(147);
    var BufferUtil = __webpack_require__(21);
    var $ = __webpack_require__(15);

    var Hash = module.exports;

    Hash.sha1 = function(buf) {
      $.checkArgument(BufferUtil.isBuffer(buf));
      return crypto.createHash('sha1').update(buf).digest();
    };
    ...

And then when I looked at module 147 (I.E. the crypto module) I was seeing nothing there:

/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {

/***/ },

After a while of searching I took a look in the Angular-CLI code and saw that part of the webpack config (addon/ng2/models/webpack-build-common.ts) was this:

node: {
      global: 'window',
      crypto: 'empty',
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

When I remove crypto: 'empty' everything builds correctly with the crypto module getting pulled in.

So my question is, why have you specified that crypto should be empty? Is there any way to fix this more permanently?

jmc265 avatar Aug 04 '16 10:08 jmc265

Update on Angular 6 @blascone solution won't work with the most recent Angular, as the file has been moved elsewhere.

Check out my gist https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d

niespodd avatar May 06 '18 11:05 niespodd

@filipesilva Please, we gotta have a hook into the webpack config to allow advanced users to tweak certain settings, without having to eject (which causes a huge amount of overhead).

You have people rewriting the node_modules files, to achieve what should be simple.

Proposal Doing an ng serve/whatever calls a hook file, where you can customize the webpack config related to the current ng command.

function webpackHook(config) {
   config.node = {
       crypto: true,
   }

   const args = require('yargs').argv;
   if (args.stats) {
    try {
         console.log('Adding Stats Plugin');
         const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
         config.plugins.push(new BundleAnalyzerPlugin());
      } catch (e) {
         console.error('webpack-bundle-analyzer not installed - `npm i webpack-bundle-analyzer --save-dev`');
      }
   }

   return config;
}

A hook file like this would probably remove the need to eject in the first place.

larssn avatar May 07 '18 17:05 larssn

I couldn't agree more with @larssn . Just a simple hook would easily remove our need to eject (we just need a single webpack plugin). This is primarily why we can't even upgrade to Angular 6 as the cli is missing the eject feature. Ejecting the project is a huge pain and makes upgrades much more difficult.

vincentjames501 avatar May 17 '18 12:05 vincentjames501

@larssn I'd suggest you create a new ticket with this request instead of in a closed ticket.

michael-letcher avatar May 20 '18 22:05 michael-letcher

@michael-letcher Thanks Michael, I did just that.

Upvote it to show your support. https://github.com/angular/angular-cli/issues/10954

larssn avatar May 22 '18 13:05 larssn

I'm getting this with mammoth.js (.docx importer):

WARNING in ./node_modules/mammoth/node_modules/sax/lib/sax.js Module not found: Error: Can't resolve 'stream' in 'C:\Users\My NameKoodaus\project-name\node_modules\mammoth\node_modules\sax\lib' ERROR in ./node_modules/mammoth/lib/docx/docx-reader.js Module not found: Error: Can't resolve 'path' in 'C:\Users\My name\Koodaus\project-name\node_modules\mammoth\lib\docx'

I've tried reading all the discussions, but haven't found a specific way to solve this.

Just to clarify - if I would approach the creator of this specific library, what should I tell him/her to fix this? Does adding typings help? Or what is the instruction to give so that their library would work with Angular6?

lehtiniemi avatar Jun 15 '18 13:06 lehtiniemi

@lehtiniemi : i might miss something but this doesn't seem related to crypto library

Asone avatar Jun 15 '18 15:06 Asone

@Asone Ah, yes. It is related to this: https://github.com/angular/devkit/issues/967 but in this thread filipesilva redirected the discussion into this thread. Or maybe he just mentioned it's discussed here, in this case my mistake. But the issue seems to have the same change in Angular CLI as the root cause.

lehtiniemi avatar Jun 15 '18 16:06 lehtiniemi

I have the same error with tensorflow.js I can make any angular applications using the newest tesnsorflow versions.

the issue can be found here https://github.com/tensorflow/tfjs/issues/494

ghost avatar Jul 07 '18 11:07 ghost

Having similar problems when trying to build an Electron app using Angular 6 and AppAuth-JS. The AppAuth module is saying it can't resolve 'crypto' (along with a bunch of other modules).

Is there still no workaround for this?

adamayoung avatar Jul 30 '18 13:07 adamayoung

@admeister you could use the patch workaround. Create a patch.js file and make sure to run it postinstall

"postinstall": "node patch.js"

A patch file that works for me

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);
  }
  var result = data.replace(/node: false/g, 'node: {crypto: true, stream: true}');

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

RedaKhyatti avatar Jul 31 '18 03:07 RedaKhyatti

@filipesilva I do not believe this issue persist after 2 years.

You guys at angular-cli are killing the adoption of Angular in the development of distributed applications, which needs crypto to Web3.js work properly.

carlosfaria94 avatar Aug 18 '18 11:08 carlosfaria94

I tried this and works

In webpack.config

module.exports = {
  // .....
  externals: {
    fs: 'commonjs fs',
    path: 'commonjs path',
    crypto: 'commonjs crypto'
  }
}

This solved (for me) a problem with fs and another problem with crypto.randomBytes

renatocassino avatar Aug 23 '18 14:08 renatocassino

@carlosfaria94 By following the browser instructions for web3.js, it can be used successfully without any modifications. Specifically the CDN based approach which also has the advantage of simplified license compliance.

It is also important to note that crypto is not being stripped out of anything. The module only exists within the Node.js platform. Browser platforms do not have such a module. A cross-platform library should ideally contain versions targeting both of the major platforms. There is in fact a browser platform specific API for cryptography (details) which will (for major browsers) leverage the underlying operating system's cryptography support.

Also, if Node.js's crypto is absolutely required and a javascript version of the algorithms is acceptable to the project's requirements, crypto-browserify can be used in combination with a tsconfig path mapping to map crypto to the package.

clydin avatar Aug 23 '18 16:08 clydin

@carlosfaria94, if you want to use angular for Ethereum projects maybe you can use @ngeth instead of web3... It's built on top of angular and doesn't require crypto. It's still an early stage project, but you can already do JSON-RPC calls and use Contracts (bonus: it supports ABIEncoder V2).

GrandSchtroumpf avatar Aug 23 '18 16:08 GrandSchtroumpf

Hi guys, I found a more permanent way of making crypto available for angular 6. We can use Custom Angular CLI builds with Angular 6 :

1 - install @angular-builders/custom-webpack : npm i -D @angular-builders/custom-webpack

2 - Add custom builder in angular.json : In angular.json > project > architect > build > builder replace current value with : @angular-builders/custom-webpack:browser

3 - Create a file webpack.config.js at the root of the project : This will be loaded by the new builder (by default the filename is webpack.config.js but you can have a custom one if needed see here. Note : This will append your config to the default webpack config from angular.

4 - Add node support in webpack.config.js : Here is what is needed for web3 for example.

module.exports = {
  node: {
    crypto: true,
    http: true,
    https: true,
    os: true,
    vm: true,
    stream: true
  }
}

Thanks a lot to Evgeny Barabanov for his amazing article on this subject. Please read and clap his article if you think this is useful. There is a bonus inside that explains how to keep using ng serve with custom builders.

GrandSchtroumpf avatar Oct 07 '18 13:10 GrandSchtroumpf

Please note that the project is not actually using node’s crypto (which uses the operating systems underlying implementations) with the settings. But rather a JavaScript partial implementation of the module. This applies to the others as well.

clydin avatar Oct 07 '18 14:10 clydin

@clydin thanks for the suggestion to use path mapping in tsconfig.json, works like a charm.

studds avatar Oct 22 '18 22:10 studds

We are suffering this same issue. After upgrading from Angular 2.0.0 to Angular 6.1.10 we are using the CLI for ng build and we have no more web pack. Our web app is using pdf and jpeg and tiff images heavily. We are using the tiff.js library and the ng build is resulting in:

ERROR in ./node_modules/tiff.js/tiff.min.js Module not found: Error: Can't resolve 'crypto' in 'C:\Users\jkahl1\Source\Repos\servicecenter-fe\node_modules\tiff.js' ERROR in ./node_modules/tiff.js/tiff.min.js Module not found: Error: Can't resolve 'fs' in 'C:\Users\jkahl1\Source\Repos\servicecenter-fe\node_modules\tiff.js' ERROR in ./node_modules/tiff.js/tiff.min.js Module not found: Error: Can't resolve 'path' in 'C:\Users\jkahl1\Source\Repos\servicecenter-fe\node_modules\tiff.js'

We tried: angular.json - "scripts": ["./node_modules/tiff.js/tiff.min.js"] and get the same results. Is there a CLI only way to get this library to build? Please provide guidance.

JoeKahl avatar Jan 02 '19 15:01 JoeKahl

Have you tried to use custom builders?

  1. Install the builders : npm install --save-dev @angular-builders/custom-webpack @angular-builders/dev-server.

  2. Update angular.json In angular.json change :

  • The builder of build (for ng build) with @angular-builders/custom-webpack:browser
  • The builder of serve (for ng serve) with @angular-builders/dev-server:generic
  1. Append the default webpack config Create a webpack.config.js file at the root of the project :
module.exports = {
  node: {
    path: true,
    crypto: true,
    fs: 'empty'
  }
}

GrandSchtroumpf avatar Jan 02 '19 15:01 GrandSchtroumpf