Merge pull request #39 from ChainSafe/dapplion/fix-default-export

Use Object.assign to fix default import
This commit is contained in:
Cayman 2020-11-29 10:21:01 -07:00 committed by GitHub
commit c0723488d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 3 deletions

View File

@ -4,7 +4,7 @@ import {bls as blsHerumi} from "./herumi";
export type Implementation = "herumi" | "blst-native"; export type Implementation = "herumi" | "blst-native";
// TODO: Use a Proxy for example to throw an error if it's not initialized yet // TODO: Use a Proxy for example to throw an error if it's not initialized yet
export let bls: IBls; export const bls: IBls = {} as IBls;
async function getImplementation(impl: Implementation = "herumi"): Promise<IBls> { async function getImplementation(impl: Implementation = "herumi"): Promise<IBls> {
switch (impl) { switch (impl) {
@ -13,11 +13,12 @@ async function getImplementation(impl: Implementation = "herumi"): Promise<IBls>
return blsHerumi; return blsHerumi;
case "blst-native": case "blst-native":
// Lazy import native bindings to prevent automatically importing binding.node files
if (typeof require !== "function") { if (typeof require !== "function") {
throw Error("blst-native is only supported in NodeJS"); throw Error("blst-native is only supported in NodeJS");
} }
// eslint-disable-next-line @typescript-eslint/no-require-imports // eslint-disable-next-line @typescript-eslint/no-require-imports
return require("./blst"); return require("./blst").bls;
default: default:
throw new Error(`Unsupported implementation - ${impl}`); throw new Error(`Unsupported implementation - ${impl}`);
@ -25,7 +26,10 @@ async function getImplementation(impl: Implementation = "herumi"): Promise<IBls>
} }
export async function init(impl: Implementation): Promise<void> { export async function init(impl: Implementation): Promise<void> {
bls = await getImplementation(impl); // Using Object.assign instead of just bls = getImplementation()
// because otherwise the default import breaks. The reference is lost
// and the imported object is still undefined after calling init()
Object.assign(bls, await getImplementation(impl));
} }
export default bls; export default bls;