node.jspostgresql

Unable to import Client from node-pg


I am trying to use Postgresql in a Node project. I am using modular imports, so I am having issues importing 'pg':

import * as pg from 'pg'
const { Client } = pg
let client = new Client()

leading to this error

        let client = new Client()
                     ^
TypeError: Client is not a constructor

I've looked at a couple other questions similar to this, but still have issues:

import { native as pg } from 'pg';
let client = new pg.Client()

leading to this error:

import { native as pg } from 'pg';
         ^^^^^^
    SyntaxError: Named export 'native' not found. The requested module 'pg' is a CommonJS module, which may not support all module.exports as named exports.

Does anyone know what I can try to make this import correctly?


Solution

  • From the error suggestion, pg is a CommonModule which may not support all module.exports as named exports.

    change the import from

    import * as pg from 'pg'
    

    to

    import pg from 'pg'
    

    will solve the import problem.