4

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?

7
  • Change const PACKAGE_NAME = require("PACKAGE_NAME"); to import PACKAGE_NAME from "PACKAGE_NAME";. Typescript requires import statements. Commented Feb 23, 2022 at 23:01
  • node runs JS scripts. TS isn't valid JS and needs to be compiled before it can be run in node. Either compile the app with TS or use ts-node Commented Feb 23, 2022 at 23:01
  • @code Well, I am not able to use import. I have update my question with more info. Commented Feb 23, 2022 at 23:10
  • TypeScript is NOT JavaScript, and NodeJS can't run TypeScript. TypeScript is run by compiling it to real JavaScript, then running it with Node. You can use ts-node for this, which compiles and runs your TS files in one command. Commented Feb 23, 2022 at 23:14
  • @EstusFlask I am pretty much new with NodeJS, as well with TypeScript. I didn't know about ts-node, but I read about it now. Commented Feb 23, 2022 at 23:19

1 Answer 1

1

TypeScript Modules documentation for its export = syntax suggests (unless it is badly written)

 export =  object_or_class

to allow the module to be imported as a CommonJS module using require in node.

Exporting an object using export in index.ts:

 const exports = { 
     start   // plus any other exports as properties
 };
 export = exports;

followed by requiring it in app.ts as

 const index = require(".directoryPath/index.js");
 const start = index.start

may solve the issue.

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah thanks that worked. But along with ts-node package. Main problem was that I didn't compile TS, as others suggested.
The answer addresses the wrong point. export is supposed to be paired with import..require TS construct. This is said on the page that was linked. const index = require(".directoryPath/index.js") is still type-unsafe with export = or not, while using import index = require(".directoryPath/index.js") in uncompiled script would make Node fail.
@EstusFlask I did think the documentation lacked clarity if you didn't know what it meant already - and it leaves open the question iof wheterh yu can import compiled ts code from vanilla Javascript at all In the absence of other information, should I assume app.ts will also fail to import dotenv, express and http modules because its not using import= syntax? If you could provide a more accurate answer it would be most appreciated - particularly if I can then delete this one!
I'll try to write a comprehensive answer. There will be no problem with importing compiled TS because it compiles to .js+.d.ts files, so compiled app is legit JS. The problem in the OP is that node ran uncompiled TS. As long as the app stays legit JS with .ts extensions and not using any TS-specific features, it runs. As for importing with require, const express = require('express') is also legit JS so it will work as is in both JS and TS, it;s just a function call. It's just not suitable in TS code because express is any without using special import...requre syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.