0

I have JS module which will be used inside react project (CRA).

index.js looks like,

export { EvtScoket } from './socket';

socket.js looks like

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 is like

{
  "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
      }
    ]
  ]
}

When I transpiled this code and used it React App it gives

TypeError: eventtalk_core___WEBPACK_IMPORTED_MODULE_7__.EvtSocket is not a constructor

It's imported and used like

import { EvtSocket } from 'evt-core';

...
 constructor(){
   ...
   this.socket = new EvtSocket('xxx');
 }

The initial error was with classProperties that's why I need to setup babel.

If I console.log(EvtScoket) it output undefined

When I import the socket file directly as evt-core/lib/socket it works seems something wrong with export in index.js

user2473015
  • 1,128
  • 2
  • 18
  • 37

2 Answers2

1

In your socket.js file, you export your class as a default export.

This means you have to import it like this:

import EvtSocket from './socket.js`

You can find more information about imports from MDN Docs

Matthis
  • 131
  • 4
  • 1
    Whilst this is correct, we can assume that the author is importing the file from the `index.js` file that he has listed in his question. In that index file, he is using a named export rather than a default. – tombraider Feb 12 '19 at 10:35
1

There could be a few reasons here, but it looks like you have a typo in your export:

export { EvtScoket } from './socket'; // typo in "Socket", EvtScoket/EvtSocket

import { EvtSocket } from 'evt-core'; // importing a named export that does not exist

Fix that typo and see if things start working again. A quick test would be to just import the incorrectly typed module, e.g.

import { EvtScoket } from 'evt-core';
tombraider
  • 1,048
  • 9
  • 18