我有 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/