Automating umd export to esm import in Rollupjs

Viewed 419

I have a bit perplexing case about default exports currently.

node --version -> v16.1.0, rollup -> 2.50.4, via @open-wc/building-rollup ^1.10.0 and update separately.

In bn.js there seem to be UMD export as far I understand as

if (typeof module === 'object') {
    module.exports = BN;
  } else {
    exports.BN = BN;
  }

  BN.BN = BN;
  BN.wordSize = 26;

then it is imported in other file BigNumber.ts as

import _BN from "bn.js";
import BN = _BN.BN;

However, in my build I receiver error

[!] Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules@ethersproject\bignumber\lib.esm\bignumber.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
node_modules@ethersproject\bignumber\lib.esm\bignumber.js (11:7)
9: import _BN from "bn.js";
10: var BN = _BN.BN;
11: import { hexlify, isBytes, isHexString } from "@ethersproject/bytes";
^
12: import { Logger } from "@ethersproject/logger";
13: import { version } from "./_version";
Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules@ethersproject\bignumber\lib.esm\bignumber.js

[!] Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules@ethersproject\bignumber\lib.esm\bignumber.js https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module node_modules@ethersproject\bignumber\lib.esm\bignumber.js (11:7) 9: import _BN from "bn.js"; 10: var BN = _BN.BN; 11: import { hexlify, isBytes, isHexString } from "@ethersproject/bytes"; ^ 12: import { Logger } from "@ethersproject/logger"; 13: import { version } from "./_version"; Error: 'default' is not exported by node_modules\bn.js\lib\bn.js, imported by node_modules@ethersproject\bignumber\lib.esm\bignumber.js

All right! I read from https://nodejs.org/api/esm.html and https://github.com/evanw/esbuild/issues/532 and https://github.com/rollup/rollup/issues/3514#issuecomment-640020081 (+ https://github.com/webpack/webpack/issues/11014#issuecomment-641550630 and https://sokra.github.io/interop-test/#rollup), for a good measure for lengthy, discussion about the issue (and other less authoritative places) and then I think I could perhaps just patch manually bn.js and its package.json in node_modules.

So off I go, copy-paste bn.js to bn.esm.js and alter its export to

export default { BN }

and add "module": "lib/bn.esm.js"

And indeed, it succeeds! Now there is however other includes with a similar issue.

This is puzzling, since in rollups.config.js I have

plugins: [
    resolve({ browser: true, preferBuiltins: true }),
    commonjs()
  ]

which I thought does something similar already. Am I mistaken? Could something like tsconfig.json settings interfere with the process? If it matters, the project/configuration that produces this is at https://github.com/veikkoeeva/erc1155sample/blob/main/web/rollup.config.js#L25.

0 Answers
Related