繁体   English   中英

如何从 index.js 中获取 TS 文件?

[英]How to require a TS file from index.js?

我刚刚从 react-express-starter 创建了一个应用程序。 在里面我有一个“服务器”文件夹,nodejs 使用它来创建后端。 在这个文件夹中,我有一个 index.js 文件:

const express = require('express');
const app = express();

const { Test } = require('./test/index.ts');

app.listen(3001, () => {
  console.log('Express server is running on localhost:3001');
  Test.run();
});

我需要从 ts 文件中调用一个方法,

服务器/测试/test.ts:

export class Test {
    static run(){
        console.log('OK THIS WORKS');
    }
}

服务器/测试/index.ts

export { Test as test} from './test';

运行服务器:

export { Test as test } from './test';
^^^^^^

SyntaxError: Unexpected token export

另一个尝试,将其添加到 index.js 的第一行:

import { Test as test } from './test';

结果:

import { Test as test } from './test';
       ^

SyntaxError: Unexpected token {

现在更改 index.js 中的第一行:

import * as test from './test';

结果:

import * as test from './test';
       ^

SyntaxError: Unexpected token *

我如何让事情发挥作用?

基本上我们必须将 typescript 文件从 ts 编译为 js。 然后只有我们可以导入到 js 文件中。 所以,我想建议所有后端代码都应该在 javascript 或 typescript 中维护

您可以使用上述任何其他入门项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM