Skip to content

Instantly share code, notes, and snippets.

@Jaakkonen
Created July 8, 2024 23:18
Show Gist options
  • Select an option

  • Save Jaakkonen/e5749893dc4bedb96cf5859cedb97481 to your computer and use it in GitHub Desktop.

Select an option

Save Jaakkonen/e5749893dc4bedb96cf5859cedb97481 to your computer and use it in GitHub Desktop.
Importing CJS module from ESM context
// Old code when having "type": "commonjs" in package.json and "module": "commonjs" in tsconfig.json
import { UndirectedGraph } from 'graphology'

Now changing to "type": "module" in package.json causes following error report:

import { UndirectedGraph } from 'graphology';
         ^^^^^^^^^^^^^^^
SyntaxError: Named export 'UndirectedGraph' not found. The requested module 'graphology' 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 'graphology';
const { UndirectedGraph } = pkg;

Doing this suggested fix makes UndirectedGraph be any type. However the type cannot be imported like

import type { UndirectedGraph } from 'graphology'
import pkg from 'graphology';
const { UndirectedGraph } = pkg; // ERROR! Cannot shadow variable

So we're left with importing the type as some other name

import type { UndirectedGraph as UndirectedGraphType} from 'graphology'
import pkg from 'graphology';
const { UndirectedGraph } = pkg;

const graph: UndirectedGraphType = new UndirectedGraph() // ERROR! Unsafe cast any

So to have the type come to the imported actual runtime variable we need to do something like:

import type { UndirectedGraph as UndirectedGraphType} from 'graphology'
import pkg from 'graphology';
const { UndirectedGraph }: { UndirectedGraph: typeof UndirectedGraphType } = pkg;

const graph: UndirectedGraphType = new UndirectedGraph()

Is this really the only way of replacing this one line import in the CommonJS world when transitioning to ESM?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment