[英]Import statement does not work in 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
但是当我尝试运行npm run start
...
你的 tsconfig.json 怎么样?
我假设您缺少一些配置,这些配置可以将 typescript 文件编译为节点可以运行的兼容 javascript,这是应该工作的 tsconfig.json 示例
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"preserveConstEnums": true,
"strict": true,
"target": "es2017",
}
所以基本上你需要有moduleResolution
到node
https://www.typescriptlang.org/docs/handbook/module-resolution.html
也不要忘记节点不运行 ts 文件,你需要先用 tsc 编译。 或者,如果您愿意,您可以随时运行npx ts-node index.ts
编辑:
ts-node 它的作用是首先将您的代码从 ts 编译为 js 并使用生成的 js 运行它节点,您可以查看有关 ts 节点的更多信息https://github.com/TypeStrong/ts-node 。
如果你想避免使用 ts-node ,你总是可以先使用npx tsc
编译,它是 typescript 的编译器,一旦你有了 javascript,你可以运行node index.js
或简单地node .
. 请注意,您必须使用 ts 配置上的outDir
检查 js 文件的输出文件夹的位置,如果缺少outDir
配置,则会在 ts 存在的同一位置添加 js 文件https://www.typescriptlang.org /docs/handbook/compiler-options.html
如果您想使用import/export
语法,您有以下选项:
esm
npm 包将此添加到您的 package.json 中:
{
"type": "module"
}
并将您的启动脚本更改为: "start": "node index.js"
(假设您使用的是 node > v13.3.0)。 如果您使用的是 node v12 或更高版本,您可以尝试: node --experimental-modules index.js
esm
包:此处的文档: https ://github.com/standard-things/esm
不过,您需要先将.ts
文件编译为.js
文件。 请参阅TypeScript 文档了解如何执行此操作。
据我所知,你还不能在 node js 中使用 import 语句。 但是您可以使用实验功能(.mjs 文件)。
本文详细解释了模块/文件的导入。
我正在使用 ts-node 这对我有用
import {ClassName} from './path/to/file.js/' //not file.ts
即使您的文件名是 file.ts 使用 file.js 也可以
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.