I have index.ts and inside of it I have something like:
const start = () => {...}
Now I have app.ts that looks like this:
const dotenv = require('dotenv');
dotenv.config();
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const PORT = 4001 || process.env.PORT;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
// I want to import and call start like this : start()
});
My package.json looks like this:
{
"name": "...",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
}
}
and tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"allowJs": true,
"checkJs": true,
"outDir": "./built",
"allowSyntheticDefaultImports": true,
"module": "CommonJS"
}
}
The thing is, I can't use import directive at all with this setup, so I guess I am doing something wrong.
If I use import, I get :
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
If I put in package.json “type” : “module”, then I get:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"
so, one pulls another...
How to import this function in app.ts from index.ts?
const PACKAGE_NAME = require("PACKAGE_NAME");toimport PACKAGE_NAME from "PACKAGE_NAME";. Typescript requires import statements.import. I have update my question with more info.ts-nodefor this, which compiles and runs your TS files in one command.TypeScript. I didn't know about ts-node, but I read about it now.