metaplex-foundation / js

A JavaScript SDK for interacting with Metaplex's programs
357 stars 182 forks source link

TypeError: Metaplex is not a constructor #384

Closed royalrust closed 1 year ago

royalrust commented 1 year ago

I encounter a strange problem and confused me for several days. in a class definition:

...
const { Connection } = require('@solana/web3.js');
const { Metaplex } = require('@metaplex-foundation/js');
...
class MyAccount {
  constructor(args) {
    ...
    this.connection = null;
    this.metaplex = null;
  }

  async getConnection() {
    if (!this.connection) {
      this.connection = new Connection(clusterUrl, 'confirmed');
    }
    return this.connection;
  }

  async getMetaplex() {
    if (!this.metaplex) {
      const connection = await this.getConnection();
      this.metaplex = new Metaplex(connection);
    }
    return this.metaplex;
  }
  ...
}
module.exports = MyAccount;

In test case, getMetaplex() return the expected result and no error occured. But when I use yarn start and in browser(chrome), the browser console says: Uncaught (in promise) TypeError: Metaplex is not a constructor. and error points to the source line: this.metaplex = new Metaplex(connection);

Any idea? Thanks.

lorisleiva commented 1 year ago

Hi there 👋

It looks like you're trying to import an ESM module in CommonJS.

If you're writing code for the browser, I recommend using ESM imports (import { Metaplex } from '...') unless you have a bundler that can fix that for you.

Closing this as this is not an issue with the SDK.