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 add node 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
Related
I'm getting a SyntaxError when running a TypeScript-compiled JS file [via TypeORM].
I have the following files:
// ./src/entity/Bird.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
#Entity()
export class Bird {
#PrimaryGeneratedColumn()
id: number;
#Column()
kingdom: string;
#Column({length: 300})
phylum: string;
#Column()
class: String;
#Column({type: 'simple-array'})
colors: string[];
#Column({default: false})
isActive: boolean;
#Column({type: 'bigint', width: 100, default: Date.now()})
timestamp_u: number;
}
// ./init.ts
import 'reflect-metadata';
import { createConnection } from 'typeorm';
async function start() {
// initialize database
let connection = await createConnection();
// close connection
await connection.close();
}
start().catch(console.error);
// ./ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "my~password",
"database": "sandbox",
"synchronize": true,
"logging": false,
"entities": [
"dist/src/entity/**/*.js",
"src/entity/**/*.ts"
]
}
// ./tsconfig.json
{
"compilerOptions": {
"lib": [
"es5",
"es6"
],
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"exclude": ["node_modules", "dist", "out"]
}
In package.json, type is set to commonjs [for ts-node to work properly];
I'm compiling TypeScript to JavaScript:
npx tsc
Then I'm running the JavaScript via Node:
node ./dist/init.js
When I do this, I get the following error:
Bird.ts:1
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^
SyntaxError: Cannot use import statement outside a module
The problem goes away when I change my ormconfig.json to this:
...
"entities": [
"dist/src/entity/**/*.js"
]
...
Note: I've removed the entities directory for TypeScript files.
However, I need to re-include that directory when I use ts-node.
My questions are:
Why is Node [via TypeORM I surmise] giving me an error regarding a .ts file when I'm running a .js file?
Is there some configuration setting I can make to have both directories in place and not get the error?
You must set type to module in package.json e.g:
"type": "module"
I have a TS project with the following configuration:
tsconfig.json (partial)
{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "src",
"esModuleInterop": true,
},
"include": [
"src"
]
}
I have a dependency on the stripe NPM package:
{
// ...
"dependencies": {
"stripe": "^8.45.0",
}
}
Then I have the following files:
src/routes/payments/index.ts
src/stripe/index.ts
I am having some trouble with imports in src/routes/payments/index.ts. I want to import the stripe library, not my own code.
This works:
// Uses me the 'Stripe' constructor which is the default export from the package
const stripe = require('stripe')('KEY');
This does not work:
import Stripe from 'stripe';
const stripe = new Stripe('KEY');
I get the following error:
Module '"PROJECT/src/stripe/index"' has no default export.
How do I disambiguate and tell TS I want to use stripe from node_modules?
Can you try to update the tsconfig.json file like this:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/*"
]
}
}
}
I am working in an Nx monorepo workspace. The workspace structure is something like below:
The api is a NestJS app, and the data-access-scripts-execute is a NestJS lib.
I don't know how I should import and use the mentioned lib controllers inside my api app. The following is my code:
api's AppModule:
import { Module } from '#nestjs/common';
import { ConfigModule, ConfigService } from '#nestjs/config';
import { MongooseModule } from '#nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
// This line says 'Cannot find module '#something/data-access-scripts-execute'
// or its corresponding type declarations.'
import { SomeController } from '#something/data-access-scripts-execute';
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, expandVariables: true }),
MongooseModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
uri: 'mongodb://localhost/something',
useFindAndModify: false,
}),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
lib's Controller:
import { Controller, Post } from '#nestjs/common';
import { SomeService } from './some.service';
import { SomeEntity } from './schemas/some.schema';
#Controller('some-address')
export class SomeController {
constructor(private readonly _service: SomeService) {}
#Post()
async create(): Promise<SomeEntity> {
console.log('create called');
return this._service.create();
}
}
I should also mention that:
All of my Angular libs can see other Angular libs
My api app can see all of my Angular libs
All of my NestJS libs cannot see other libs
All of my NestJS libs cannot be seen by other libs and apps
By the word see I actually mean #something which my project name.
The following is also my tsconfig.base.json file which is located in the root of the workspace:
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"module": "esnext",
"lib": ["es2017", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
"#something/system": ["libs/system/src/index.ts"],
"#something/feature-some-angular-lib": [
"libs/feature-some-angular-lib/src/index.ts"
],
"#something/feature-some-angular-lib": [
"libs/feature-some-angular-lib/src/index.ts"
],
"#something/shared": ["libs/shared/src/index.ts"],
"#something/data-access-scripts-execute": ["libs/data-access-scripts-execute/src/index.ts"]
}
},
"exclude": ["node_modules", "tmp"]
}
I should also say that the image is not complete becuase of privacy reasons.
I ran into a similar issue and the reason for that was "baseUrl": "." property in the app's tsconfig.app.json
Try to remove that and see if it resolves your issue. This is only my guess and I cannot say much without looking at your tsconfig.app.json
I have a declaration file written for extsting npm package, but seems like one method was not declared, I try to declare it, but get an error. Help me please.
structure of existing d.ts file:
declare module "mongoose" {
...
class Document {}
interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties {
increment(): this;
remove(fn?: (err: any, product: this) => void): Promise<this>;
...
}
}
I try to add to interface Document method deleteOne. My custom.d.ts:
declare module "mongoose" {
interface Document {
deleteOne(fn?: (err: any, product: this) => void): Promise<this>;
}
}
But still I get an error "Property 'deleteOne' does not exist on type".
Here is my tsconfig.json if you need:
{
"compilerOptions": {
"module": "commonjs",
"removeComments": true,
"esModuleInterop": true,
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"pretty": true,
"resolveJsonModule": true,
"sourceMap": true,
"target": "ES2018",
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*"
]
}
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.spec.ts"
]
}
My custom.d.ts file located in 'src/' dir.
OK! Now I know this is expected behavior of ts-node: https://github.com/TypeStrong/ts-node#missing-types
I have configured paths settings in tsconfig.json, and now everything is working:
"paths": {
"mongoose": ["src/custom.d.ts"],
"*": [
"node_modules/*"
]
}
defining the Mongoose interface
// types/mongoose/index.d.ts
declare module 'mongoose' {
namespace Mongoose {
export interface MyInterface {
name: number;
}
}
}
usage
// app.ts
import mongoose, { Mongoose } from 'mongoose';
const a: Mongoose.MyInterface = {
name: 122
};
I have also added "typeRoots": ["./node_modules/#types", "./server/types"], to my tsconfig file
does this help
I have an Angular CLI 6 project that I'm trying to get tests working in. Here is a snippet from my test:
beforeEach(() => {
spyOn(console, 'info');
TestBed.configureTestingModule({
providers: [
ConsoleLoggerEffects,
provideMockActions(() => actions),
],
});
effects = TestBed.get(ConsoleLoggerEffects);
});
The ConsoleLoggerEffects has a single dependency injected - the Actions observable:
#Injectable()
export class ConsoleLoggerEffects {
constructor(private actions$: Actions) { }
}
This is exactly following the ngrx example, but it's not working.
When I go to run the tests, Angular complains Error: Can't resolve all parameters for ConsoleLoggerEffects: (?). I added a console.log to the factory function passed to provideMockActions, and it was never executed, so the factory function isn't even being called.
Even if I don't use provideMockActions and specify a provider myself, it also doesn't work:
TestBed.configureTestingModule({
providers: [
ConsoleLoggerEffects,
{ provide: Actions, useValue: new ReplaySubject(1)}
]
});
Anyone know what might be going on?
I had the same issue, and I finally could fix it by editing my tsconfig.spec.json, then removing node_modules and reinstalling them.
This is how my TS Spec configuration file looks like now:
But you can follow the one in the example-app on https://github.com/ngrx/platform
{
"extends": "../tsconfig.json",
"compilerOptions": {
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2017", "dom"],
"outDir": "../out-tsc/spec",
"module": "commonjs",
"target": "es6",
"types": ["jest", "node"],
"baseUrl": ".",
"rootDir": "./"
},
"files": [
"polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}