我有 JS 模块,将在 React 项目(CRA)中使用。
index.js
看起来像,
export { EvtScoket } from './socket';
socket.js
看起来像
import openSocket from 'socket.io-client';
export default class EvtSocket {
constructor(socketURL) {
this.socket = openSocket(socketURL);
}
joinAsParticipant = () => {
this.socket.emit('participantJoin', 'session');
};
joinAsSpeaker = () => {
this.socket.emit('speakerJoin', 'lobby');
};
subscribeToInitialQuesitons = (cb) => {
this.socket.on('initialQuestions', (questions) => {
cb(null, questions);
});
};
subscribeToQuestion = (cb) => {
this.socket.on('newQuestionGot', (question) => cb(null, question));
};
sendQuestion = (question) => {
this.socket.emit('newQuestionOn', question);
};
}
babelrc
就像
{
"presets": [
[
"@babel/preset-env",
{
// "targets": {
// "esmodules": true
// },
"modules": "commonjs"
}
]
// "@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-classes",
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-transform-runtime",
"@babel/plugin-syntax-export-extensions",
[
"@babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
当我转译这段代码并使用它时,它给出了 React App
类型错误:eventtalk_core___WEBPACK_IMPORTED_MODULE_7__.EvtSocket 不是构造函数
它的导入和使用就像
import { EvtSocket } from 'evt-core';
...
constructor(){
...
this.socket = new EvtSocket('xxx');
}
最初的错误与 classProperties 相关,这就是我需要设置 babel 的原因。
如果我console.log(EvtScoket)
它输出undefined
当我直接将套接字文件导入为evt-core/lib/socket
时,它的工作似乎与index.js中的导出有问题
最佳答案
这里可能有几个原因,但看起来您的导出中有一个拼写错误:
export { EvtScoket } from './socket'; // typo in "Socket", EvtScoket/EvtSocket
import { EvtSocket } from 'evt-core'; // importing a named export that does not exist
修复该拼写错误并查看是否可以再次正常工作。一个快速测试是仅导入错误键入的模块,例如
import { EvtScoket } from 'evt-core';
关于javascript - 转译代码给出 TypeError :is not a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54645831/