[英]Angular: Can't use 'require' keyword
在我的應用程序中,我需要使用require
關鍵字來導入一些東西。 但我不能。 它顯示以下錯誤:
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
}
}
請指出哪里出了問題
[注意,對於這部分錯誤
嘗試
npm i @types/node
然后將node
添加到 tsconfig 中的類型字段。
我做了 npm install @types/node --save 然后向 tsconfig.json 添加了行,但錯誤保持不變]
無論您是否甚至可以在瀏覽器中使用 postgresql (您不能)。 要像這樣導入 package,您必須安裝類型,然后可以使用import
語句:
npm i -D @types/pg
import { Pool, Client } from 'pg';
讓我再說一遍,package pg
僅適用於node.js
環境,不適用於瀏覽器:
Node.js 的非阻塞 PostgreSQL 客戶端
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.