如何在React(+TypeScript)应用中集成Stockfish.js?
Hey there! Let's work through getting Stockfish.js integrated into your chess app—those issues you're hitting are super common when setting up WebAssembly-based engines like Stockfish, so let's break them down one by one and fix them.
First off, make sure you’re using precompiled Stockfish.js files (not raw source code from the repo). The official releases include a ready-to-use stockfish.js and matching stockfish.wasm file. Using these avoids compilation headaches right out the gate.
Your CompileError about the magic word is definitely a path issue—your worker was loading an HTML file (the <!DO is the start of <!DOCTYPE html>) instead of the Stockfish script. Here’s the correct way to set up the Web Worker:
Place files properly:
Dropstockfish.jsandstockfish.wasminto yourpublicfolder (or a subfolder likepublic/engines/—just keep track of the path).Create a dedicated worker wrapper:
Make a new file calledstockfish.worker.jsin yourpublicfolder. This acts as a middleman to load Stockfish correctly:// Adjust the path if you put Stockfish in a subfolder importScripts('stockfish.js'); // Listen for commands from your main app self.onmessage = (e) => { if (e.data.command === 'uci') { stockfish.postMessage('uci'); } else if (e.data.command === 'position') { stockfish.postMessage(`position fen ${e.data.fen}`); } else if (e.data.command === 'go') { stockfish.postMessage('go depth 10'); } // Add other commands as needed }; // Send Stockfish's output back to your main app stockfish.onmessage = (e) => { self.postMessage(e.data); };Load the worker in your main code:
In your app’s main JavaScript file:// Path is relative to your public folder const stockfishWorker = new Worker('/stockfish.worker.js'); // Send a test command to Stockfish stockfishWorker.postMessage({ command: 'uci' }); // Handle responses from Stockfish stockfishWorker.onmessage = (e) => { console.log('Stockfish says:', e.data); // Parse the UCI output here for your chess logic };
This fixes the magic word error because we’re explicitly loading the correct Stockfish script instead of accidentally pulling in an HTML file.
STOCKFISH() Issue If you want to load Stockfish directly in the main thread (not recommended for UI responsiveness, but possible), wait for the script to fully load before calling it:
In your index.html:
<script src="%PUBLIC_URL%/stockfish.js"></script> <script> // Wait for the page and script to finish loading window.addEventListener('load', () => { const stockfish = window.STOCKFISH(); stockfish.onmessage = (e) => console.log(e.data); stockfish.postMessage('uci'); }); </script>
Most precompiled Stockfish.js files are UMD-formatted, so they’ll expose the STOCKFISH() function globally once loaded.
require() Approach If you’re using a bundler like Webpack or Vite:
- First install the npm package:
npm install stockfish - Then import it in your code:
const Stockfish = require('stockfish'); const stockfish = Stockfish(); stockfish.onmessage = (msg) => console.log(msg.data); stockfish.postMessage('uci'); - If you hit WebAssembly bundling errors, add this to your webpack config:
module.exports = { module: { rules: [ { test: /\.wasm$/, type: 'webassembly/async', }, ], }, };
- Check your network tab: Use your browser’s dev tools to confirm
stockfish.jsandstockfish.wasmare loading with a 200 status code (not 404). - Use the latest release: Old versions of Stockfish.js might have compatibility issues with modern browsers.
- Stick to Web Workers: Even if the global approach works, Web Workers keep your chess app’s UI responsive during Stockfish’s calculations.
Hope this gets you up and running with Stockfish! If you hit any specific follow-up errors, feel free to share more details.
内容的提问来源于stack exchange,提问作者Ties Mulder




