Mon*_*nic 10 javascript typescript
我读到了有关 javascript 中的导入和导出声明的内容。然后我尝试使用“import”关键字在文件中导入一个类。但是,尽管已经阅读了 Node.js 中模块的声明,但在执行 Node 时还是会出现错误。
我的索引.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!");
})
Run Code Online (Sandbox Code Playgroud)
我的课程/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;
Run Code Online (Sandbox Code Playgroud)
我的package.json
但是当我尝试跑步时npm run start...
你的 tsconfig.json 怎么样?
我假设您缺少一些配置,这些配置可以将打字稿文件编译为节点可以运行的兼容 JavaScript,这是一个应该可以工作的 tsconfig.json 示例
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"preserveConstEnums": true,
"strict": true,
"target": "es2017",
}
Run Code Online (Sandbox Code Playgroud)
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 tsctypescript 的编译器进行编译,一旦你有了 javascript,你就可以运行node index.js或简单地运行node .. 请注意,您必须使用outDirts 配置检查 js 文件的输出文件夹,如果outDir缺少配置,则会在 ts 存在的同一位置添加 js 文件
https://www.typescriptlang.org/docs /handbook/compiler-options.html
| 归档时间: |
|
| 查看次数: |
21424 次 |
| 最近记录: |