在TypeScript中使用stockfish.js时遭遇模块解析错误
问题:Webpack构建时无法解析stockfish模块
执行npm install stockfish后配置了相关代码,但构建时抛出Module not found: Error: Can't resolve 'stockfish'错误,Webpack在node_modules/stockfish目录下找不到对应扩展名的文件。
相关文件内容
getBestMove.ts
import stockfish from 'stockfish'; const fen = '3r1r1k/pp2Nqbp/3Rb2p/2P1pp2/7P/N1P3P1/PP2QP2/R3K3 w - - 2 30' interface TBestMoveResponse { bestMove: string | null; } export const getBestMove = async () => { const engine = stockfish(); const details = await new Promise<TBestMoveResponse>((resolve, reject) => { let bestMove = null; engine.onmessage = (line: string) => { if (line.startsWith('bestmove')) { const tokens = line.split(' '); bestMove = tokens[1]; resolve({ bestMove }); } }; engine.postMessage(`position fen ${fen}`); engine.postMessage(`go depth 20`); }); engine.postMessage('quit'); return details; }
stockfish.d.ts
declare module 'stockfish' { const stockfish: any; export default stockfish; }
tsconfig.json
{ "compilerOptions": { "target": "es2020", "module": "ES2020", "rootDir": "./", "sourceMap": true, "strict": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "moduleResolution": "node", "resolveJsonModule": true, "outDir": "./dist", "typeRoots": ["./node_modules/@types", "./src/types/libraries"], "baseUrl": "./src", "types": ["node"] }, "include": ["index.ts", "src/**/*"], "exclude": ["node_modules"] }
webpack.config.cjs
const path = require('path'); const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); const slsw = require('serverless-webpack'); const webpack = require('webpack'); const TerserPlugin = require('terser-webpack-plugin'); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); module.exports = { entry: slsw.lib.entries, experiments: { outputModule: true, }, target: 'node', mode: slsw.isLocal ? 'development' : 'production', performance: { hints: false, }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: ['babel-loader', 'ts-loader'], }, ] }, node: false, optimization: { minimize: true, minimizer: [new TerserPlugin({ terserOptions: { keep_classnames: true, keep_fnames: true, } })], }, resolve: { extensions: ['.cjs', '.mjs', '.js', '.ts'], plugins: [ new TsconfigPathsPlugin({ configFile: path.resolve(__dirname, 'tsconfig.json'), }), ] }, plugins: [ new ForkTsCheckerWebpackPlugin(), ], output: { path: slsw.lib.webpack.isLocal ? path.join(__dirname, '.webpack') : path.join(__dirname, 'dist'), chunkFormat: 'module', library: { type: "module", }, }, };
错误详情
Module not found: Error: Can't resolve 'stockfish'
无扩展名 <path>/node_modules/stockfish 不是文件 .cjs <path>/node_modules/stockfish.cjs 不存在 .mjs <path>/node_modules/stockfish.mjs 不存在 .js <path>/node_modules/stockfish.js 不存在 .ts
解决方案
1. 检查stockfish包的入口配置
打开node_modules/stockfish/package.json,查看main或module字段的指向。如果入口文件在子目录(比如dist/stockfish.js),可以直接修改导入语句指定路径:
import stockfish from 'stockfish/dist/stockfish.js';
2. 调整Webpack的解析配置
如果不想修改导入路径,在Webpack的resolve配置中添加mainFields,确保优先读取包的package.json中指定的入口:
resolve: { extensions: ['.cjs', '.mjs', '.js', '.ts'], mainFields: ['main', 'module'], // 优先按package.json的main字段查找入口 plugins: [ new TsconfigPathsPlugin({ configFile: path.resolve(__dirname, 'tsconfig.json'), }), ] },
3. 替换为Node.js兼容版本
你的Webpack target是node,但普通stockfish包通常是浏览器端的,依赖WebWorker无法在Node.js环境运行。可以卸载现有包,安装Node.js适配版本:
npm uninstall stockfish npm install stockfish-node
然后更新导入语句和类型声明:
// getBestMove.ts import Stockfish from 'stockfish-node'; export const getBestMove = async () => { const engine = new Stockfish(); // 后续逻辑保持不变 }
// stockfish.d.ts declare module 'stockfish-node' { class Stockfish { constructor(); onmessage: (line: string) => void; postMessage: (cmd: string) => void; quit(): void; } export default Stockfish; }
4. 补充缺失的扩展名
如果stockfish的入口文件是.wasm这类未在Webpack解析列表中的格式,需要添加到resolve.extensions:
resolve: { extensions: ['.cjs', '.mjs', '.js', '.ts', '.wasm'], // ...其他配置 }
内容的提问来源于stack exchange,提问作者a94
相关产品推荐
相关产品推荐

