Error [ERR_REQUIRE_ESM]: require() of ES Module in fastify project - node.js

Trying to import fastify-openapi-glue in my fastify project but getting error ERR_REQUIRE_ESM and I'm using typescript in the application.
Code looks like below
routes.ts file
/* eslint-disable node/no-unsupported-features/es-syntax */
import { FastifyInstance } from 'fastify';
// import openapiGlue from 'fastify-openapi-glue';
// const openapiGlue = await import("fastify-openapi-glue");
import { Service } from '../controllers/service';
async function loadOpenapiGlue() {
const openapiGlueModule = await import('fastify-openapi-glue');
return openapiGlueModule.default;
}
const options = {
specification: './openapi.yaml',
service: new Service()
};
export default async (app: FastifyInstance): Promise<void> => {
const openapiGlue = await loadOpenapiGlue();
app.register(openapiGlue, options);
};
tsconfig.json file
{
"ts-node": {
"require": ["tsconfig-paths/register"]
},
"compilerOptions": {
"alwaysStrict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"removeComments": true,
"lib": ["ES2020"],
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"baseUrl": "./src",
"rootDirs": ["src"],
"outDir": "dist",
"plugins": [],
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"strictNullChecks": true,
"target": "ES2020",
"types": ["node", "jest"],
"paths": {
"#/*": ["*"]
}
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
Note:
After updating the module under tsconfig.json as mentioned in other stackoverflow answer as "module": "ES2022", I'm getting error like SyntaxError: Cannot use import statement outside a module

Related

Cannot find module 'react' error when using next-auth in nodejs

Works fine in my local environment but when i try to deploy my server getting
Error: Cannot find module 'react'
on /project/src/node_modules/next-auth/react/index.js
it seems like next-auth using React for some parts.
my ts config:
{
"compilerOptions": {
"target": "es2022",
"lib": ["ES2022"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "ES2022",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"exclude": ["node_modules"],
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node"
}
}
my package.json:
I've used ts-node --esm for build command

TSError: ⨯ Unable to compile TypeScript

My Project is built on Nodejs with TypeScript
I'm getting this compilation error in my Node.js app:
E:\NodeProjects\esshop-mongodb-nodejs\node_modules\ts-node\src\index.ts:859
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
TSError: ⨯ Unable to compile TypeScript:
src/posts/post.dto.ts:5:10 - error TS1219: Experimental support for decorators is a feature that is
subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.
5 public author: string;
src/posts/post.dto.ts
import { IsString } from 'class-validator';
class CreatePostDto {
#IsString()
public author: string;
#IsString()
public content: string;
#IsString()
public title: string;
}
export default CreatePostDto;
my tsconfig.json:
{
"compilerOptions": {
"sourceMap": true,
"target": "ES6",
"outDir": "./dist",
"baseUrl": "./src",
"alwaysStrict": true,
"noImplicitAny": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
I installed latest version: [ts-node, typescript]
project repo in github:
https://github.com/barrytestfl/esshop-mongodb-nodejs
My problem solved by change this options in tsconfig.json:
"esModuleInterop": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true
This worked for me
my tsconfig.json file :
{
"compilerOptions": {
"sourceMap": true,
"target": "es2019",
"outDir": "./dist",
"baseUrl": "./src",
"alwaysStrict": true,
"noImplicitAny": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}

How to use tsconfig-paths with ts-node

How do you setup paths with typescript to run with ts-node? And later compile paths to absolute paths when compiling?
I have following very minimal structure:
koki.ts:
export const calculate = (a: number, b: number) => {
return a + b;
};
index.ts:
import { calculate } from "#koki/koki";
const result = calculate(1, 2);
console.log(result);
tsconfig.json:
{
"ts-node": {
"transpileOnly": true,
"require": ["tsconfig-paths/register"]
},
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
"skipLibCheck": true,
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"#/*": ["*"],
"#koki/*": ["koki/*"]
}
},
"exclude": ["node_modules"],
"include": ["./src/**/*.ts"]
}
I am getting:
ts-node src/index.ts
Error: Cannot find module '#koki/koki'
Require stack:
- /home/pwnage/Documents/github/test-node/src/index.ts
In my case, I added the -r option to ts-node scripts
package.json
"scripts": {
"start": "ts-node -r tsconfig-paths/register src/index.ts",
}
ts-node works well in these codes
import { env } from "#/config/env";

Getting typescript TS1135: Argument expression expected. with routing-controllers #Req

I am using NodeJS Express routing-controllers with TypeScript, the following code doesn't compile when I added the #Req()/#Res() decorators, if I remove them it compiles fine.
#Service()
#JsonController()
export default class FlightsController {
constructor(
#Inject('flightsService') private flightsService : FlightsService)
{}
#Get('/flights')
getFlights = async (#Req() req: Request, #Res() res: Response) => {
Logger.debug(`Entering getFlights...`);
try {
const flightsList = await this.flightsService.getFlights();
res.send(flightsList);
} catch (error) {
res.status(500).send(error);
}
}
}
How can I fix this issue...
this is my tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"sourceMap": true,
"outDir": "dist",
"allowJs": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"dom",
"es6"
],
"baseUrl": "./src",
"paths": {
"#/*": [
"./*"
]
}
},
"exclude": [
"node_modules",
"dist"
],
"include": [
"src/**/*.ts",
"tests/**/*.test.ts"
],
"files": [
"src/index.ts"
]
}

ts-node unable to compile JSX tags

I am trying to compile JSX tags into HTML and then flushing them into an HTML file but somehow ts-node fails to compile the following piece of code.
private index = (request: Request, response: Response) => {
// const component = React.createElement(Index, {key: 1, name: "Aman Sharma"}) // this works
const component = <Index key={1} name="Aman Sharma" /> // throws error
const html = ReactDOMServer.renderToString(component)
fs.writeFileSync('website/index.html', html);
response.status(200).send();
}
This is the error being thrown.
I have included "jsx": "react" in my tsconfig.json. My configuration is as follows:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"es2015",
"dom"
],
"moduleResolution": "node",
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"outDir": "build",
"jsx": "react",
"allowJs": true
},
"include": [
"src/**/*.{ts,tsx}"
],
"exclude": [
"node_modules"
]
}
This fixed the issue for me
"jsx": "react-jsx",

Resources