javascript - 导入语句在 typescript 中不起作用

标签 javascript typescript

我读到了有关 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

enter image description here

但是当我尝试运行npm run start...

enter image description here

最佳答案

你的 tsconfig.json 怎么样?

我假设您缺少一些配置,这些配置可以将 typescript 文件编译为节点可以运行的兼容 JavaScript,这是一个应该可以工作的 tsconfig.json 示例

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "preserveConstEnums": true,
    "strict": true,
    "target": "es2017",
}

所以本质上你需要有 moduleResolutionnode 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/

相关文章:

javascript - 为什么我会收到 JavaScript Puppeteer 错误 : "ECONNREFUSED"?

javascript - 调整 slickgrid 列标题的大小会导致它与正文不对齐

javascript - 创建一个二维关联数组 javascript(与 php 关联数组相同)

reactjs - React Custom Hook with Typescript Type error "Property ' x' 在类型 'interface | (({ target }: any) => void)' .ts(2339) 上不存在"

javascript - 静态删除对象键 JavaScript

javascript - 在 IE9 中建立内存

javascript - 通过单击 Javascript 中的 nextdate 按钮来增加日期、日、月和年

angular - 如何从一个组件调用另一个组件的方法 [Angular]

angular - 引用错误 : IDBIndex is not defined Angular SSR

javascript - 在 json_to_sheet 之后使用 XLSX js 对列进行排序和过滤