简体   繁体   中英

How to import chess.js into Create React App

I want to use the chess.js npm library inside my Create React App, but I keep getting the error that "Chess is not a constructor". Here's my code:

import React from 'react';
import './App.css';
const { Chess } = require('chess.js');

class App extends React.Component 
{
    constructor(props) {
        super(props);
        this.state = { board: '' };

        let game = new Chess();
        this.state.board = game.ascii();
    }

    render() {
        return (
            <div className="App">
                {/* <InputForm name="Moves: "/> */}
                <p>{ this.state.board }</p>
            </div>
        );
    }
}

export default App;

package.json:

{
  "name": "blind-chess",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "chess.js": "^0.11.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Does any body know what I'm doing wrong? My code looks like the example code provided in the documentation but it's still not working. https://www.npmjs.com/package/chess.js

Do you have you're package.json? There is some additional documentation https://github.com/jhlywa/chess.js/blob/master/README.md that may be helpful

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