我读到了有关 javascript 中的导入和导出声明的内容。然后我尝试使用“import”关键字在文件中导入一个类。但是,尽管已经阅读了 Node.js 中模块的声明,但在执行 Node 时还是会出现错误。
我的index.ts:
import Server from "./classes/server";
import router from './routes/router';
const server = new Server();
server.app.use('/', router);
server.start(() => {
console.log("server starting!");
})
我的类/server.ts
import { SERVER_PORT } from './../global/enviroment';
import express from 'express';
class Server {
public app: express.Application;
public port: number;
constructor(){
this.app = express();
this.port = SERVER_PORT;
}
start(callback: any){
this.app.listen(this.port, callback);
}
}
export default Server;
我的package.json
但是当我尝试运行npm run start
...
最佳答案
你的 tsconfig.json 怎么样?
我假设您缺少一些配置,这些配置可以将 typescript 文件编译为节点可以运行的兼容 JavaScript,这是一个应该可以工作的 tsconfig.json 示例
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"preserveConstEnums": true,
"strict": true,
"target": "es2017",
}
所以本质上你需要有 moduleResolution
到 node
https://www.typescriptlang.org/docs/handbook/module-resolution.html
另外不要忘记,node 不运行 ts 文件,您需要先使用 tsc 进行编译。或者,如果您愿意,也可以随时运行 npx ts-node index.ts
编辑:
ts-node 它的作用是先将你的代码从 ts 编译为 js,然后使用生成的 js 运行它的 Node,你可以查看有关 ts Node 的更多信息 https://github.com/TypeStrong/ts-node .
如果你想避免使用 ts-node,你总是可以先使用 npx tsc
进行编译,这是来自 typescript 的编译器,一旦你有了 javascript,你就可以运行 node index.js
或简单的node .
。
请注意,您必须使用 ts 配置上的 outDir
检查 js 文件的输出文件夹,如果缺少 outDir
配置,则会将 js 文件添加到ts 存在于同一位置
https://www.typescriptlang.org/docs/handbook/compiler-options.html
关于javascript - 导入语句在 typescript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59196715/