Пакет NPM [bitcoinjs-lib] не совместим с IE v11 - PullRequest
0 голосов
/ 24 октября 2019

Я добавляю поддержку IE v11 для веб-приложения. bitcoinjs-lib пакет содержит функцию стрелки, которая приводит к сбою IE v11.

Я добавил babel-polyfill, response-app-polyfill / ie11, url-search-params-polyfill и Reaction-app-polyfill / stable, обеспечивающий большую часть поддержки IE v11, ожидает пакет bitcoinjs-lib.

Изображение в браузере IE v11

.bashrc

{ 
  "plugins": [
    ["@babel/plugin-transform-arrow-functions"],
    [
      "module-resolver", {
      "root": ["./"],
      "alias": {
        "~": "./"
      }
    }]
  ],
  "presets": [
    [
      "next/babel",
      {
        "preset-env": {
          "useBuiltIns": "usage"
        }
      }
    ]
  ]
}

исходный код внутри пакета

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const parser_1 = require('../parser');
function combine(psbts) {
  const self = psbts[0];
  const selfKeyVals = parser_1.psbtToKeyVals(self);
  const others = psbts.slice(1);
  if (others.length === 0) throw new Error('Combine: Nothing to combine');
  const selfTx = getTx(self);
  if (selfTx === undefined) {
    throw new Error('Combine: Self missing transaction');
  }
  const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals);
  const selfInputSets = selfKeyVals.inputKeyVals.map(input => getKeySet(input));
  const selfOutputSets = selfKeyVals.outputKeyVals.map(output =>
    getKeySet(output),
  );
  for (const other of others) {
    const otherTx = getTx(other);
    if (
      otherTx === undefined ||
      !otherTx.toBuffer().equals(selfTx.toBuffer())
    ) {
      throw new Error(
        'Combine: One of the Psbts does not have the same transaction.',
      );
    }
    const otherKeyVals = parser_1.psbtToKeyVals(other);
    const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals);
    otherGlobalSet.forEach(
      keyPusher(
        selfGlobalSet,
        selfKeyVals.globalKeyVals,
        otherKeyVals.globalKeyVals,
      ),
    );
    const otherInputSets = otherKeyVals.inputKeyVals.map(input =>
      getKeySet(input),
    );
    otherInputSets.forEach((inputSet, idx) =>
      inputSet.forEach(
        keyPusher(
          selfInputSets[idx],
          selfKeyVals.inputKeyVals[idx],
          otherKeyVals.inputKeyVals[idx],
        ),
      ),
    );
    const otherOutputSets = otherKeyVals.outputKeyVals.map(output =>
      getKeySet(output),
    );
    otherOutputSets.forEach((outputSet, idx) =>
      outputSet.forEach(
        keyPusher(
          selfOutputSets[idx],
          selfKeyVals.outputKeyVals[idx],
          otherKeyVals.outputKeyVals[idx],
        ),
      ),
    );
  }
  return parser_1.psbtFromKeyVals(selfTx, {
    globalMapKeyVals: selfKeyVals.globalKeyVals,
    inputKeyVals: selfKeyVals.inputKeyVals,
    outputKeyVals: selfKeyVals.outputKeyVals,
  });
}
exports.combine = combine;
function keyPusher(selfSet, selfKeyVals, otherKeyVals) {
  return key => {
    if (selfSet.has(key)) return;
    const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0];
    selfKeyVals.push(newKv);
    selfSet.add(key);
  };
}
function getTx(psbt) {
  return psbt.globalMap.unsignedTx;
}
function getKeySet(keyVals) {
  const set = new Set();
  keyVals.forEach(keyVal => {
    const hex = keyVal.key.toString('hex');
    if (set.has(hex))
      throw new Error('Combine: KeyValue Map keys should be unique');
    set.add(hex);
  });
  return set;
}

.next.config.js

const fs = require('fs')
const dotenv = require('dotenv')
const webpack = require('webpack')
const withCSS = require('@zeit/next-css')
const withFonts = require('next-fonts')
const withImages = require('next-images')
const withPlugins = require("next-compose-plugins")
const withTM = require('next-transpile-modules');

const getEnvFile = () => {
  const fileName =  process.env.NODE_ENV == 'development' ? '.env' : `.env.${process.env.NODE_ENV}`
  return fs.readFileSync(fileName)
}

const envConfig = dotenv.parse(getEnvFile())

const nextConfig = {
  webpack(config) {
    config.plugins.push(new webpack.EnvironmentPlugin(envConfig))
    const originalEntry = config.entry;
    config.entry = async () => {
      const entries = await originalEntry();
      if (entries['main.js'] && !entries['main.js'].includes('./polyfills.js')) {
          entries['main.js'].unshift('./polyfills.js');
      }

      return entries;
    };
    config.module.rules.push({
      test: /\.js$/,
      include: [/node_modules\/bitcoinjs-lib/],
      use: {
        loader: "next/babel",
        options: {
          presets: ["@babel/presets-env", {modules: false}],
          plugins: ["@babel/plugin-transform-arrow-functions"],
        },
      },
    })
    return config
  },
  exportPathMap: async function(defaultPathMap) {
    return {
      '/'                      : { page: '/people' },
      '/dashboard'             : { page: '/dashboard' },
      '/tenant-investigator'   : { page: '/tenant_investigator' },
      '/pricing-history'       : { page: '/pricingHistory' },
      '/algorithm'             : { page: '/algorithm' },
      '/group'                 : { page: '/group' },
      '/group-detail'          : { page: '/group_detail' },
      '/investigation'         : { page: '/investigation' },
      '/login'                 : { page: '/login' },
      '/map'                   : { page: '/map' },
      '/people'                : { page: '/people' },
      '/people-report'         : { page: '/people_report' },
      '/report'                : { page: '/report' },
      '/people-detail'         : { page: '/people_detail' },
      '/pricing-history'       : { page: '/pricingHistory' },
      '/settings'              : { page: '/settings' },
      '/tenant'                : { page: '/tenant' },
      '/wallets'               : { page: '/wallets' },
      '/transactions'          : { page: '/transactions' },
      '/taxable-event'         : { page: '/taxable_event' },
      '/subpoena-upload'       : { page: '/subpoenaUpload' },
      '/people-subpoena-upload': { page: '/peopleSubpoenaUpload' },
      '/subpoena-transactions' : { page: '/subpoenaTransactions' },
      '/event-detail'          : { page: '/peopleEvent' },
      '/grand-unified'         : { page: '/grandUnified' },
            '/blocks'                : { page: '/blocks' },
      '/person-edit'           : { page: '/personEdit' },
      '/addresses'             : { page: '/addresses' },
      '/exchanges'             : { page: '/exchanges' }
    }
  }
}
console.log(nextConfig)

// module.exports = withPlugins([withCSS, withFonts, withImages], nextConfig)
module.exports = withPlugins(
  [
    [
      withTM,
      {
        transpileModules: ['bitcoinjs-lib']
      }
    ],
    withCSS,
    withFonts,
    withImages
  ],
  nextConfig
);

Как мы видим, использование функции стрелки вызывает ошибку

Я хочу пакет node_moduleбыть преобразованным в родной JavaScript для IE v11 можно легко прочитать. Когда я смотрю на источник node_module, функцию стрелки и ES6 можно увидеть в посылке.

...