简体   繁体   中英

React external script method is not defined

I need to import BlotterJS on my React projet so I set it in my index.html file as :

<script crossorigin src="https://rawgit.com/bradley/Blotter/master/build/blotter.min.js"></script>

I'm using it on my component: in componentWillMount I generate the Blotter text with my method generateText but it needs to create a new Blotter instance. Here is the component:

export class Home extends React.Component {
  constructor() {
    super()
  }
  componentWillMount() {
    this.text = this.generateText()
  }
  render() {
    return (
      <div className="container">
        <h1> Benjamin Moquet </h1>
        <div id="welcome"></div>
        <nav>
          <div className={styles.double_buttons}>
            <Link to="/about" className={`button ${styles.button_small}`}>About me</Link>
            <Link to="/work" className="button button_small">Work</Link>
          </div>
          <Link to="/contact" className="button button_large">Contact</Link>
        </nav>
      </div>
    )
  }
  generateText () {
    return new Blotter.Text("WELCOME.", {
      family : "'EB Garamond', serif",
      size : 50,
      fill : "#202020"
    })
  }
  // Things here to generate the material and create the scope, but same issue, I can't do this because it needs Blotter too
}

I'm getting the following error: 错误 I just want to be able to use the Blotter type. I don't know if I'm importing BlotterJS correctly.

Try using window.Blotter instead of Blotter .

It seems your compiler isn't finding the variable definition and throwing an error, but your logic seems fine so I would guess this will fix it.

If you are using webpack then you need to configure Blotter as an external library. Refer webpack documentation: https://webpack.js.org/configuration/externals/

Essentially, you can add following to your webpack.config.js

externals: {
    Blotter: 'Blotter'
}

After that you can use it as any other library:

import Blotter from 'Blotter';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM