contentful / contentful-management.js

JavaScript library for Contentful's Management API (node & browser)
https://contentful.github.io/contentful-management.js
MIT License
266 stars 98 forks source link

contentful is undefined when importing via ES6 style #2241

Open y-lobau opened 5 months ago

y-lobau commented 5 months ago

The documentation states:

import contentful from 'contentful-management'
const client = contentful.createClient(
  {
    // This is the access token for this space. Normally, you get the token in the Contentful web app
    accessToken: 'YOUR_ACCESS_TOKEN',
  },
  { type: 'plain' }
)

When running this code from within the Contentful App (react), the contentful variable is undefined.

image

I was able to make it work with the following instead:

import { createClient } from "contentful-management";
const client =createClient...

Node.js: v21.7.1 contentful-management: 11.24.3

dvejmz commented 3 months ago

I can confirm I have the same issue in version 11.25.3 of the contentful-management package and that @y-lobau 's workaround works for me too.

It would be good to have this addressed though as the ES6 import example in the documentation does not work!

marcogrcr commented 1 week ago

@y-lobau Interesting, are you using some compiler/transpiler that modifies the import somehow? I wound up on this issue because I actually got the opposite behavior:

package.json

{
  "name": "example",
  "version": "1.0.0",
  "private": "true",
  "main": "index.js",
  "type": "module",
  "dependencies": {
    "contentful-management": "11.24.3"
  }
}

index.js

import contentful from "contentful-management";

console.log(contentful.createClient);

Running node . yields:

[Function: createClient]

If I change index.js as follows:

import { createClient } from "contentful-management";

console.log(createClient);

I get:

file:///(...)/index.js:1
import { createClient } from "contentful-management";
         ^^^^^^^^^^^^
SyntaxError: Named export 'createClient' not found. The requested module 'contentful-management' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'contentful-management';
const { createClient } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:134:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:217:5)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:120:12)

Node.js v21.7.1
y-lobau commented 1 week ago

My .tsconfig looks as follows: image image Maybe it has something to do with the situation.