Search code examples
reactjswebpackreact-reduxbotframeworkgatsby

WebpackError: TypeError: Object(...) is not a function gatsbyjs build error (botframework-webchat)


I'm trying to integrate botframework-webchat to a gatsby.js website, gatsby develop builds successfully, however when i run the production build using the command gatsby build, it throws the following error.

 > 15 |     const store = createStore({}, ({ dispatch }) => next => action => {
[1]      |                            ^
[1]   16 |       if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
[1]   17 |         dispatch({
[1]   18 |           type: 'WEB_CHAT/SEND_EVENT',
[1] 
[1] 
[1]   WebpackError: TypeError: Object(...) is not a function
[1]   
[1]   - MinimizableWebChat.js:15 
[1]     src/lib/webchat/MinimizableWebChat.js:15:31

run the develop build: gatsby develop (builds successfully).
run the production build: gatsby build (throws error)

below is the complete code for MinimizableWebChat.js which is taken from microsoft BotFramework-Webchat

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createStore } from 'botframework-webchat';
import classNames from 'classnames';
import WebChat from './WebChat';
import { checkTokenExpirationDate, createToken } from './utils/tokenDefs';
import './utils/fabric-icons-inline.css';
import './MinimizableWebChat.scss';

const USR_BOT_TKN = 'USR_TKN';

const MinimizableWebChat = ({ lang = 'en', darkMode = false }) => {
  useEffect(() => {
    return () => {
      localStorage.removeItem(USR_BOT_TKN);
      setToken(null);
    };
  }, [lang]);

  const store = useMemo(
    () =>
      createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
          dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
              name: 'webchat/join',
              value: {
                language: lang,
              },
            },
          });
        } else if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
          if (action.payload.activity.from.role === 'bot') {
            setNewMessage(true);
          }
        }

        return next(action);
      }),
    [lang]
  );

  const [loaded, setLoaded] = useState(false);
  const [minimized, setMinimized] = useState(true);
  const [newMessage, setNewMessage] = useState(false);
  const [token, setToken] = useState();

  const handleFetchToken = useCallback(async () => {
    if (!token) {
      const userToken = localStorage.getItem(USR_BOT_TKN);
      const isValidToken = checkTokenExpirationDate(userToken);
      if (userToken && isValidToken) {
        return setToken(userToken);
      } else {
        const res = await fetch(createToken().uriGenerateToken, createToken().params);
        const { token } = await res.json();
        localStorage.setItem(USR_BOT_TKN, token);
        setToken(token);
      }
    }
  }, [setToken, token]);

  const handleMaximizeButtonClick = useCallback(async () => {
    setLoaded(true);
    setMinimized(false);
    setNewMessage(false);
  }, [setMinimized, setNewMessage]);

  const handleMinimizeButtonClick = useCallback(() => {
    setMinimized(true);
    setNewMessage(false);
  }, [setMinimized, setNewMessage]);

  return (
    <div className='minimizable-web-chat'>
      <button
        className={classNames(
          lang === 'ar' ? 'maximize left' : 'maximize right',
          darkMode ? 'dark' : ''
        )}
        onClick={minimized ? handleMaximizeButtonClick : handleMinimizeButtonClick}>
        {minimized ? (
          <img
            src={darkMode ? '/open_chat_icon_black.svg' : '/open_chat_icon.svg'}
            alt='Open chat button icon'
          />
        ) : (
          <span className='ms-Icon ms-Icon--Cancel' />
        )}
        {newMessage && minimized && (
          <span className='ms-Icon ms-Icon--CircleShapeSolid red-dot' />
        )}
      </button>

      {loaded && (
        <div
          className={classNames(
            lang === 'ar' ? 'chat-box left' : 'chat-box right',
            // side === 'left' ? 'chat-box left' : 'chat-box right',
            minimized ? 'hide' : '',
            darkMode ? 'dark' : ''
          )}>
          <header>
            <img src='/logo.svg' alt='Logo' />
          </header>
          {lang && (
            <WebChat
              className='react-web-chat'
              onFetchToken={handleFetchToken}
              store={store}
              token={token}
              lang={lang}
              darkMode={darkMode}
            />
          )}
        </div>
      )}
    </div>
  );
};

export default MinimizableWebChat;

Solution

  • I've been aware of you have followed up the suggested link https://www.gatsbyjs.com/docs/debugging-html-builds/#fixing-third-party-modules to fix window issue.

    BUT it this way is likely to prevent webpack compile the commonjs web chat packages properly which ended up with the issue.

    I was also aware of the configuration the stage of build-html isn't called during dev that's why you wouldn't see the error as you yarn start // gatsby develop.

    However, the document also suggests another way to fix is to use code splitting technique by using loadable-component. Personally, I think this way is best for you project since the chat is supposed to be rendered at the client side only.

    Here's a few thing you would change:

    • Remove your configuration in gatsby-node:
    // Remove this
    actions.setWebpackConfig({ ... }}
    
    • Apply the yarn add @loadable/component to your repo:
    
    // Install `yarn add @loadable/component` // or with npm i -D yarn add @loadable/component
    
    // Make your chat component to be loadable:
    // pages/index.js
    
    - import MinimizableWebChat from '../components/webchat/MinimizableWebChat'
    
    + import loadable from '@loadable/component'
    + const MinimizableWebChat = loadable(() => import('./../components/webchat/MinimizableWebChat'))