关于在TypeScript中导入模块

zqdjd7g9  于 2023-01-10  发布在  TypeScript
关注(0)|答案(1)|浏览(274)

我有这样的文件结构:

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

在我的src/index.ts上,我尝试了以下方法:

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)}`);

一切都运转得很好。
但是,我需要使用Express.js,因此我更新了代码:

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)}`);

现在,我有这个错误:

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?

这是我的tsconfig.json:

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

这是我的包裹

{
  "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"
  }
}

我不能将tsconfig.json设置为使用module ='node '的原因是因为我希望能够正确地导入我自己的模块,并且我还需要在我的index.ts文件中使用最顶层的await ...
我更改package.jsontsconfig.json的所有尝试都导致以下结果之一:
1.我无法使用最顶层的await
1.我无法导入/找到我的模块
1.我无法导入任何节点模块(在本例中为express)
有人能帮帮我吗?谢谢

a8jjtwal

a8jjtwal1#

我的tsconfig.json很可能,注意添加“类型”:“模块”到package.json,“模块分辨率”:“节点16”和
从'./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"]
}

相关问题