How to use tsconfig-paths with ts-node - node.js

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";

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

Error [ERR_REQUIRE_ESM]: require() of ES Module in fastify project

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

Q: Typescript: TS7006: Parameter implicity has any type

TS7006: Parameter 'port' implicitly has an 'any' type.
constructor(port) {
TS7006: Parameter 'message' implicitly has an 'any' type.
Emit(message) {
I'm at loss here because every other answer is to add type "any" or whatever.
In this case both port and message DO have a type, number and string respectively.
note that i don't usually work with node/typescript, so i have no clue if the config is good. Also setting strict: false and noImplicitAny: false yields similar error with Emit()
throw new TypeError(${relative(cwd, fileName)}: Emit skipped);
Also this errors come from .js files, so i guess tsc passes?
export class EventEmitter {
private port: number
constructor(port: number) {
this.port = port
...
}
public Emit(message: string) {
this.io.send(message)
}
package.json scripts
"start": "cd dashboard && (npm run dev > dashboard.log 2>&1 &) && cd .. && tsc-watch --onSuccess \"npm run watch\"",
"watch": "nodemon --watch './src/*.ts' --exec 'node --experimental-specifier-resolution=node --loader ts-node/esm' src/main.ts",
ignore dashboard part, its some svelte frontend part that needs to be run by side.
tsconfig.json
{
"include": [
"src",
"dashboard/src/**/*.d.ts",
"dashboard/src/**/*.js",
"dashboard/src/**/*.ts",
"dashboard/src/**/*.svelte"
],
"compilerOptions": {
"moduleResolution": "node",
"target": "es2018",
"module": "esnext",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"checkJs": true,
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"resolveJsonModule": true,
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"*": [
"src/*",
"node_modules/*"
]
},
"esModuleInterop": true,
}
}
Answer was to set checkJS: false and allowJS: false
If this is wrong and someone knows anything better, let me know.
thanks.

How solve experimentalDecorators warning using typescript and PM2?

I'm working on a project that uses node.js with typescript. If I run TSC or a command to build the project, it works because I have the option "experimentalDecorators": true in my tsconfig.json.
But when I put it into my dev server using pm2 with the same configuration, doesn't work using the exosystem.config.json and without.
First, I have this tsconfig.json:
{
"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,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"rootDir": "src",
"composite": true,
"declaration": true,
"noEmitOnError": false,
"preserveConstEnums": true,
},
"exclude": ["node_modules"],
"include": ["src"],
}
My project structure is:
index.ts
tsconfig.json
src/
ecosystem.config.js
My ecosystem.config.js is:
module.exports = {
apps : [{
name: "app",
script: './index.ts',
autorestart: true,
exec_mode: "fork",
watch: true,
env: {
NODE_ENV: 'development',
},
env_production: {
NODE_ENV: 'production',
},
}
],
};
And if I debug the pm2 logs I have this error:
Error
I solve this error with this ecosystem.config.js configuration:
module.exports = {
apps : [{
name: 'app',
script: './node_modules/.bin/ts-node',
args: '-P ./tsconfig.json ./index.ts',
watch: true,
restart_delay: 10000,
wait_ready: true
}],
};

Top level await gives error in build but works on dev

My code works when ran npm run dev but when I build it it gives this error. According to the docs I need target set to ES2017 or higher in tsconfig.json but I am using ESNEXT which I believe is compatible
error
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["./src"]
}
Because I was using vite in the question, vite.config.ts is what I should have been looking to edit instead of tsconfig.json
here is the fix to it
vite.config.ts
export default defineConfig({
build: {
minify: 'esbuild',
target: "esnext"
}
})

Resources