I read about import and export declarations in javascript. Then I'm trying to import a class in a file using 'import' keyword. But despite having read about the declaration of modules in node.js y get a error when execute node.
My index.ts :
import Server from "./classes/server";
import router from './routes/router';
const server = new Server();
server.app.use('/', router);
server.start(() => {
console.log("server starting!");
})
My classes/server.ts
import { SERVER_PORT } from './../global/enviroment';
import express from 'express';
class Server {
public app: express.Application;
public port: number;
constructor(){
this.app = express();
this.port = SERVER_PORT;
}
start(callback: any){
this.app.listen(this.port, callback);
}
}
export default Server;
My package.json

But when i try to run npm run start...

How is your tsconfig.json ?
I assume you are missing some configuration that that enables the compilation of the typescript file into a compatible javascript that node can run, here's an example of tsconfig.json that should work
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"preserveConstEnums": true,
"strict": true,
"target": "es2017",
}
So essentially you will need to have moduleResolution to node
https://www.typescriptlang.org/docs/handbook/module-resolution.html
Also don't forget that node doesn't run ts files, you need to compile then first with tsc. Or if you prefer you can always run npx ts-node index.ts
EDIT:
ts-node what it does is compile your code first from ts to js and run it node with the generated js, you can check more information about ts node https://github.com/TypeStrong/ts-node.
If you want to avoid to use ts-node your can always compile first using npx tsc which is the compiler from typescript, once you have the javascript you can run node index.js or simply node ..
Note that you have to check where you're output folder for the js file using the outDir on the ts configuration, if outDiris configuration is missing will add js files in the same place the ts exists
https://www.typescriptlang.org/docs/handbook/compiler-options.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With