How to do Import and Require together?
Asked Answered
H

1

2

Node v14, server backend needs Observable and connection to PostgreSql.

  • To create Observable, import { Observable } from 'rxjs'; is needed.
  • Must add "type": "module" into pakage.json else Warning: To load an ES module, set "type": "module" in the package.json
  • But it makes require not working for Postgre connection.

index.js

import { Observable } from 'rxjs';
const observable = new Observable(
  subscriber => 
  {
    ...
  });

observable.subscribe({...});
console.log('just after subscribe');

To connect to PostgreSql,

const pgp = require('pg-promise')();
const db = pgp({...});

Now getting ReferenceError: require is not defined.

How can I have both?

Hyperopia answered 24/8, 2021 at 0:9 Comment(5)
Why aren't you using the TypeScript syntax for including pg-promise?Buttons
@Buttons Following the sample import * as pgPromise from 'pg-promise'; const pgp = pgPromise({}); got TypeError: pgPromise is not a function pgp version 10.11.0Hyperopia
U need to configure your TS right, as explained there.Buttons
@Buttons I installed TS npm install typescript -g, npm install, went to typescript folder by cd node_modules\typescript, ran tsc got a help screen. So I did tsc --init, tsc --build tsconfig.json. F5, same pgPromise is not a function. Any other steps missing?Hyperopia
@Buttons Resolved without TS. Thank you anyway!Hyperopia
H
1

After much research and try, come back to the same spot, simply replace require with import. As an example of above,

Original:

const pgp = require('pg-promise')();
const db = pgp({...});

New:

import pgPromise from 'pg-promise';
const pgp = pgPromise({...});
const db = pgp({...});
Hyperopia answered 24/8, 2021 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.