In my app, i need to use the require
keyword to import something. But i can't. It shows the error below:
ERROR in src/app/components/test1/test1.component.ts:3:24 - error TS2591: Cannot find name 'require'. Do you need
to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.
3 const {Pool, Client} = require('pg');
test1.component.ts
import { Component, OnInit } from '@angular/core';
const {Pool, Client} = require('pg');
const connectionString = 'postgressql;://postgres:1@localhost:3000/test1';
const client = new Client({connectionString});
client.connect();
client.query('select * from posts',
(err, res) => {console.log(err, res);
client.end();
});
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
styleUrls: ['./test1.component.css']
})
export class Test1Component implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"es2018",
"dom"
],
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
Please point out what went wrong
[ A note that, for this part of error
Try
npm i @types/node
and then addnode
to the types field in your tsconfig.
i did npm install @types/node --save and then added lines to tsconfig.json but error stays same ]
Regardless if you can even use postgresql in the browser (which you can't). To import a package like that, you have to install the types and then you can use the import
statement:
npm i -D @types/pg
import { Pool, Client } from 'pg';
Let me just say it again though, the package pg
is just for a node.js
environment, not for a browser:
Non-blocking PostgreSQL client for Node.js