Home > Enterprise >  How to use import along with require in Javascript/Typescript?
How to use import along with require in Javascript/Typescript?

Time:02-24

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?

CodePudding user response:

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.

  • Related