javascript - 转译代码给出 TypeError :is not a constructor

标签 javascript reactjs babeljs es6-modules

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

相关文章:

javascript - Bootstrap 模式在长列表中的位置

javascript - 在 Opera 中关注跨域 Ajax

javascript - 将 D3 工具提示应用于 donut 倍数

reactjs - 如何更改 Material UI 选择边框和标签

javascript - 仅将 BabelJS 用作旧浏览器的后备

reactjs - 使用 styled-jsx 而不弹出 create-react-app

javascript - jQuery $.post 数据如果大于 0 则分配给变量

javascript - 仅在 react 中阻止特定页面的浏览器后退按钮

javascript - 将回调/ promise 从组件传递给操作创建者

javascript - NW.js + 通天塔 : ES6 import working but not export?