【问题标题】:How to require a TS file from index.js?如何从 index.js 中获取 TS 文件?
【发布时间】:2020-02-08 00:07:19
【问题描述】:

我刚刚从 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 *

我如何让事情发挥作用?

【问题讨论】:

  • import { Test as test } from './test';
  • 您好,Ihor,我已将您建议的内容添加到 index.js 文件中,结果为:C:\Source\react-express-starter-master\server\index.js:2从'./test'导入{测试作为测试}; ^ SyntaxError: Unexpected token {

标签: javascript node.js reactjs typescript


【解决方案1】:

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

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

【讨论】:

  • 感谢您分享您的存储库!那些转译让我头疼。
猜你喜欢
  • 2019-03-27
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2021-02-13
  • 1970-01-01
  • 2019-02-11
  • 2019-10-15
相关资源
最近更新 更多