javascript - 如何在 Javascript/Typescript 中使用 import 和 require?

标签 javascript node.js typescript express

我有 index.ts,里面有类似的东西:

const start = () => {...}

现在我的 app.ts 看起来像这样:

const dotenv = require('dotenv');
dotenv.config();
const express = require('express');
const app = express();
const server = require('http').createServer(app);

const PORT = 4001 || process.env.PORT;

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  // I want to import and call start like this : start()
});

我的 package.json 看起来像这样:

{
  "name": "...",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    ...
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "checkJs": true,
    "outDir": "./built",
    "allowSyntheticDefaultImports": true,
    "module": "CommonJS"
  }
}

问题是,我无法在此设置中使用 import 指令,所以我想我做错了什么。

如果我使用import,我得到:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

如果我输入 package.json “type” : “module”,那么我会得到:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

所以,一个拉另一个...

如何从index.ts导入这个函数到app.ts

最佳答案

export = 的 TypeScript 模块文档语法建议(除非写得不好)

 export =  object_or_class

允许在 Node 中使用 require 将模块导入为 CommonJS 模块。

使用 index.ts 中的 export 导出对象:

 const exports = { 
     start   // plus any other exports as properties
 };
 export = exports;

然后在 app.ts 中要求它作为

 const index = require(".directoryPath/index.js");
 const start = index.start

可能会解决问题。

关于javascript - 如何在 Javascript/Typescript 中使用 import 和 require?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71244984/

相关文章:

javascript - 创建多按钮唯一点击计数器

javascript - 从 Cloudant 获取所有文档数据,而不是 id、key、value

Typescript 装饰器和 Object.defineProperty 奇怪的行为

javascript - Angular 和 Typescript - 从管理员登录中停用其他用户时出现问题

javascript - 验证外部脚本是否已加载

javascript - 类似苹果的搜索框

javascript - node busboy + express 4 + ng-file-upload 不触发事件

angular - 如何在其中一个流依赖于另一个流的情况下使用 combineLatest?

javascript - 将连续的 ","合并为单个 ","并在一个 RegExp 中删除前导和尾随 ","

node.js - 如何在主 Handlebars 布局中编写快速 session 登录/注销的条件?