我有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,我得到:
警告:要加載 ES 模塊,請在 package.json 中設定 "type": "module" 或使用 .mjs 擴展名。
如果我輸入package.json “type” : “module”,那么我得到:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知檔案擴展名“.ts”
所以,一個拉另一個...
如何在app.tsfrom中匯入此功能index.ts?
uj5u.com熱心網友回復:
其export =語法的 TypeScript Modules 檔案建議(除非它寫得不好)
export = object_or_class
require允許使用in node將模塊作為 CommonJS 模塊匯入。
使用exportin index.ts匯出物件:
const exports = {
start // plus any other exports as properties
};
export = exports;
然后在app.ts中要求它為
const index = require(".directoryPath/index.js");
const start = index.start
可以解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432050.html
標籤:javascript 节点.js 打字稿 表示
上一篇:如何構建此服務器后端路由?
