You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在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.

Step 1: First, Grab the Correct Stockfish.js Files

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.

Step 2: Fixing the Web Worker "Magic Word" Error

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:

  1. Place files properly:
    Drop stockfish.js and stockfish.wasm into your public folder (or a subfolder like public/engines/—just keep track of the path).

  2. Create a dedicated worker wrapper:
    Make a new file called stockfish.worker.js in your public folder. 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);
    };
    
  3. 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.

Step 3: Fixing the Global 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.

Step 4: Fixing the require() Approach

If you’re using a bundler like Webpack or Vite:

  1. First install the npm package:
    npm install stockfish
    
  2. Then import it in your code:
    const Stockfish = require('stockfish');
    const stockfish = Stockfish();
    
    stockfish.onmessage = (msg) => console.log(msg.data);
    stockfish.postMessage('uci');
    
  3. If you hit WebAssembly bundling errors, add this to your webpack config:
    module.exports = {
      module: {
        rules: [
          {
            test: /\.wasm$/,
            type: 'webassembly/async',
          },
        ],
      },
    };
    
Quick Troubleshooting Tips
  • Check your network tab: Use your browser’s dev tools to confirm stockfish.js and stockfish.wasm are 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

火山引擎 最新活动