indutny / elliptic

Fast Elliptic Curve Cryptography in plain javascript
1.68k stars 373 forks source link

ES6 Modules #117

Open swansontec opened 7 years ago

swansontec commented 7 years ago

We would like to slim down our build sizes a bit, and since the only thing we need elliptic for is secp256k1 ECDH, we end up bundling a lot of unused code for other curves and algorithms. One way to solve this is to switch elliptic over to ES6 modules. This way, tree-shaking tools like rollup.js can statically analyze the import and export statements to eliminate dead code.

I would be happy to do the work if this seems worthwhile. The change would involve introducing a prepackage script that bundles the sources into a single commonJS module using rollup.js. Existing users won't notice any change thanks to the bundling, but downstream users that speak ES6 natively can do tree-shaking on the un-bundled sources.

For the unit tests, we can either run the build as part of a pretest script, or we can use a pollyfill to get module support directly in node. I've been using the pretest build approach in my own work, and it's actually pretty nice, like having a lint for your import/export statements.

Does this seem like something worthwhile?

fanatid commented 7 years ago

@swansontec do you think that it worth? not sure that I right, but I think that you will save only 27502 bytes from 137456 (20%)

3466    lib/elliptic/utils.js
32338   lib/elliptic/precomputed/secp256k1.js
36434   lib/elliptic/precomputed
1739    lib/elliptic/eddsa/signature.js
2533    lib/elliptic/eddsa/key.js
3523    lib/elliptic/eddsa/index.js
11891   lib/elliptic/eddsa
2948    lib/elliptic/hmac-drbg.js
22859   lib/elliptic/curve/short.js
9349    lib/elliptic/curve/base.js
4644    lib/elliptic/curve/mont.js
10967   lib/elliptic/curve/edwards.js
173 lib/elliptic/curve/index.js
52088   lib/elliptic/curve
6443    lib/elliptic/curves.js
2839    lib/elliptic/ec/signature.js
2570    lib/elliptic/ec/key.js
6065    lib/elliptic/ec/index.js
15570   lib/elliptic/ec
132936  lib/elliptic
424 lib/elliptic.js
137456  lib

if you really want save much space will be better drop all extra code.. for example my secp256k1 code based on elliptic is only 11313 bytes or 46057 with stripped BN -- https://github.com/cryptocoinjs/secp256k1-node/tree/c21870da22dffbf950eecd43963ba3012b91e213/lib/js

cryptocoinjs/secp256k1-node with all dependencies

$ ./node_modules/.bin/browserify elliptic.js | wc -c
451638
$ ./node_modules/.bin/browserify js.js | wc -c
263820
swansontec commented 7 years ago

Yeah, this doesn't make much sense from an effort per byte point of view. Nevertheless, the offer still stands. Tree shaking is a good technological fit for the elliptic library, and even if I don't benefit that much from it, I would still like to see it happen.

dcousens commented 7 years ago

@fanatid it could add up globally seeing as this is used in crypto-browserify