Skip to content

TwitterEmbed: require is not defined #1122

@SimonSiefke

Description

@SimonSiefke

When using react-embed with vite, in production an error message is displayed when using the Twitter Embed: ReferenceError: require is not defined
require-is-not-defined

The issue seems to be in Tweet/index.tsx:

  componentDidMount() {
    require('scriptjs')('https://platform.twitter.com/widgets.js', 'tw', () => {
      if (!this.mounted) return;
      if (!wnd.twttr) {
        // tslint:disable-next-line
        console.error('Failed to load Twitter lib.');
        return;
      }
      wnd.twttr.widgets.createTweet(this.props.id, this.refs.ref, {theme: this.props.isDark ? 'dark' : 'light'});
    });
  }

It seems in both commonjs and esm require is used, which doesn't exist for esm.

Possible solution

It seems the require could be converted to an import:

  async componentDidMount() {
    const {default: scriptjs} = await import('scriptjs');
    scriptjs('https://platform.twitter.com/widgets.js', 'tw', () => {
      if (!this.mounted) return;
      if (!wnd.twttr) {
        // tslint:disable-next-line
        console.error('Failed to load Twitter lib.');
        return;
      }
      wnd.twttr.widgets.createTweet(this.props.id, this.refs.ref, {theme: this.props.isDark ? 'dark' : 'light'});
    });
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions