最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何从index.js要求TS文件?

IT培训 admin 9浏览 0评论

如何从index.js要求TS文件?

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

我如何使事情起作用?

回答如下:

基本上,我们必须将打字稿文件从ts编译为js。然后,只有我们才能导入js文件。因此,我建议所有后端代码都应使用javascript或Typescript进行维护

  • 对于打字稿:https://github/gokulakannant/express-typescript-mongodb-starter
  • 对于Javascript:https://github/GetStream/node-express-mongo-api

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

如何从index.js要求TS文件?

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

我如何使事情起作用?

回答如下:

基本上,我们必须将打字稿文件从ts编译为js。然后,只有我们才能导入js文件。因此,我建议所有后端代码都应使用javascript或Typescript进行维护

  • 对于打字稿:https://github/gokulakannant/express-typescript-mongodb-starter
  • 对于Javascript:https://github/GetStream/node-express-mongo-api

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

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论