[英]About importing modules in TypeScript
我有这个文件结构:
∟ 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"
}
}
这是我的 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"
}
}
我无法将 tsconfig.json 设置为使用 module='node' 的原因是因为我希望能够正确导入我的(自己的)模块并且我还需要在我的index.ts
文件上使用最顶层的await
...
我所有更改package.json
或tsconfig.json
的尝试都导致:
await
谁能帮我? 谢谢
我的 tsconfig.json 可能,请注意将 "type": "module" 添加到 package.json, "moduleResolution": "Node16" 和
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"]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.