Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

338
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda