yoni
yoni

Reputation: 139

TypeError: WooCommerceRestApi is not a constructor

I was using NPM @woocommerce/woocommerce-rest-api successfully to manage API requests to Woocommerce/ WP website.

Was using babel and CJS version:

const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

But since Node 14 is offering a simple way to use ESM I have added the following configuration to the package.json, so I can use the import statement: "type": "module"

So I should have been able to use this format:

import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

But now I get this error:

file:///xxxxxx/test.js:5
const api = new WooCommerceRestApi({
            ^

TypeError: WooCommerceRestApi is not a constructor
    at file:///xxxxxxxx/test.js:5:13
    at ModuleJob.run (internal/modules/esm/module_job.js:138:23)
    at async Loader.import (internal/modules/esm/loader.js:178:24)

Why would that happen?

Upvotes: 5

Views: 1525

Answers (1)

cviller
cviller

Reputation: 306

You may have already solved this, but I ran into this issue myself and it looks to me like the esm loader is defaulting to the cjs version of the library.

This worked for me:

import pkg from '@woocommerce/woocommerce-rest-api';
const WooCommerceRestApi = pkg.default;

Yes, it is not a pretty solution, but it might be helpful for others or inspire someone to explain further. ;)

Upvotes: 19

Related Questions