无法将现有 ws 从 javascript 转换为 typescript。无法理解异步 socketHost 函数的返回类型是什么以及为什么我不能通过“this”关键字访问它们
这是代码:
const config = {
production: {
socketHost: 'wss://someName.com/ws',
},
development: {
socketHost: 'ws://localhost:5555',
},
};
module.exports = config[process.env.NODE_ENV || 'production'];
错误:
Cannot compile namespaces when the '--isolatedModules' flag is provided.
套接字.ts
import { socketHost } from 'config';
function connect():Promise<WebSocket {
return new Promise(
(resolve, reject): Promise<void> => {
const src = socketHost;
const ws = new WebSocket(src);
ws.onopen = () => {
ws.onmessage = () => resolve(ws);
};
ws.onerror = err => {
return reject(err);
};
},
);
}
class SocketService {
public constructor() {
if (!SocketService.instance) {
SocketService.instance = this;
}
this.reconnectionCount = 0;
return SocketService.instance;
}
public unsubscribe(model, data, socket = this.socket): void {
if (socket && socket.readyState === 1) {
socket.send(JSON.stringify(['leave', model, data]));
} else {
processError('unsubscribe failed');
}
}
public async initSocket() {
if (this.socket && this.socket.readyState === 1) {
return this.socket;
}
try {
const socket = await connect();
this.reconnectionCount = 0;
this.socket = socket;
return socket;
} catch (error) {
console.log('error', error);
processError(`initSocket => ${error}`, this.reconnectionCount);
if (this.reconnectionCount < 60) {
setTimeout(() => {
this.initSocket();
this.reconnectionCount = this.reconnectionCount + 1;
}, 1000);
} else {
console.info('await connection 10s');
setTimeout(() => {
this.initSocket();
}, 10000);
}
this.socket = null;
}
return null;
}
public async init() {
const ws = await this.initSocket();
if (!ws) return;
// const chainOrder = this.getChain(order);
ws.onmessage = ({ data: message }) => {
if (message) {
console.log('message', message);
const data = JSON.parse(message);
resolver(data);
}
};
ws.onerror = error => {
processError('subscribeFull err', error);
};
ws.onclose = ({ wasClean, code, reason }): void => {
if (wasClean) {
console.warn('socket closed clear');
} else {
processError('socket closed unexpected');
this.reconnectSocket();
}
console.info(`Code: ${code} reason: ${reason}`);
};
this.subscribe();
}
public async subscribe(): Promise<void> {
const { socket } = this;
try {
if (socket.readyState === 1) {
await socket.send(JSON.stringify('init'));
}
} catch (error) {
console.log('subscribe', error);
}
}
public async closeSocket(): Promise<void> {
if (this.socket) {
await this.socket.close();
}
this.reconnectionCount = 0;
}
public async reconnectSocket(): Promise<void> {
await this.closeSocket();
await this.initSocket();
await this.subscribe();
}
}
错误
"File: config/index.ts is not a module.",
在这一点上,我已经重写了整个应用程序并且我碰壁了,即使在看了 3 个小时的文档之后也不明白如何重写这部分。
任何帮助将不胜感激