About importing modules in TypeScript

1.5k Views Asked by At

I have this file structure:

∟ src
  ∟ math
    ├ funcs.ts
    ├ constants.ts
    ├ index.ts
├ index.ts

On my src/index.ts, I tried this:

import * as math from './math/index.js';

console.log(`pi = ${math.PI}`);
console.log(`The area of a circle with radius 4 is ${math.circleArea(4)}`);

and everything runs perfectly.

However, I need to use Express.js, so I updated the code:

import express from 'express';
import * as math from './math/index.js';

console.log(`pi = ${math.PI}`);
console.log(`The area of a circle with radius 4 is ${math.circleArea(4)}`);

Now, I have this error:

src/index.ts:1:21 - error TS2792: Cannot find module 'express'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

This is my tsconfig.json:

{
    "compilerOptions": {
        "outDir":"build",
        "target": "ES2022",
        "module": "ES2022"
    }
}

and this is my package.json:

{
  "name": "typescript-lab",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc",
    "start": "npm run build && node ./build/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "typescript": "^4.7.4"
  }
}

The reason I can't set tsconfig.json to use module='node' is because I want to be able to import my (own) modules correctly and I also need to use a topmost await on my index.ts file...

All my attempts to change package.json or tsconfig.json have resulted in either:

  1. I can't use a topmost await
  2. I can't import/find my modules
  3. I can't import any node module (express in this case)

Can anyone help me? Thanks

1

There are 1 best solutions below

0
On

my tsconfig.json likely, notice that add "type": "module" to package.json, "moduleResolution": "Node16" and

import * as math from './math/index.js';

{
  "compilerOptions": {
    "sourceMap": true,
    "target": "ES2022",
    "outDir": "dist",
    "baseUrl": ".",
    // "allowJs": true,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "moduleResolution": "Node16",
    "skipLibCheck": true,
    "module": "ES2022",
    "lib": [
      "dom",
      "es2015",
      "ES2016",
      "es2017",
      "ES2018",
      "ES2019",
      "ES2020",
      "ES2021",
      "ES2022",
    ],
    "paths": {
      "~controllers/*": ["./src/controllers/*"],
      "~models/*": ["./src/models/*"],
      "~middlewares/*": ["./src/middlewares/*"],
      "~services/*": ["./src/services/*"],
      "~utils/*": ["./src/utils/*"],
      "~routes/*": ["./src/routes/*"]
    }
  },
  "include": ["./src/**/*.ts"],
  "exclude": ["node_modules"],
  "files": ["global.d.ts", "declarations.d.ts"]
}