Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
How to use import along with require in Javascript/Typescript?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!