You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用chess.js与chessboard.js出现SyntaxError错误求助

解决chess.js引入时的"Unexpected token 'export'"语法错误

问题情况

你当前的引入代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.13.4/chess.js" integrity="sha512-40VRp1+fauX7g61ZdQpOiOJTkBbYwVlTLjCXHK9Svf0Mmz9K8Smg5k6LVrc0eEc9+pApf1HNL6Cim/wFqZeRkw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard-1.0.0.min.js" integrity="sha512-WfASs5HtTgTL/eZsLaOftSN9wMQl7WZGlU5UiKx/yxTViMfGh9whWRwKAC27qH8VtZJqSMqDdbq2uUb1tY3jvQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

控制台报错:

Uncaught SyntaxError: Unexpected token 'export' (at chess.js:252:1)

报错对应代码行:

export const BLACK = 'b'

错误原因

你引入的chess.js是ES模块格式,使用了ES6的export语法,但普通<script>标签默认以传统脚本模式加载,无法识别ES模块语法,因此抛出语法错误。

解决方法

方法一:将chess.js以模块方式加载

给chess.js的<script>标签添加type="module"属性,告诉浏览器以ES模块模式加载该脚本:

<script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.13.4/chess.js" integrity="sha512-40VRp1+fauX7g61ZdQpOiOJTkBbYwVlTLjCXHK9Svf0Mmz9K8Smg5k6LVrc0eEc9+pApf1HNL6Cim/wFqZeRkw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard-1.0.0.min.js" integrity="sha512-WfASs5HtTgTL/eZsLaOftSN9wMQl7WZGlU5UiKx/yxTViMfGh9whWRwKAC27qH8VtZJqSMqDdbq2uUb1tY3jvQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

使用模块模式后,需通过import语句获取chess.js的API:

import { Chess } from 'https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.13.4/chess.js';
const game = new Chess();

方法二:改用兼容全局变量的UMD版本

直接替换chess.js的链接为UMD格式版本(该版本支持传统脚本加载,会在全局暴露Chess对象):

<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.13.4/chess.min.js" integrity="sha512-60Q4w/t1a4Yg65Wb5D8eJQ8kX8W80tV3zZ5F735F+g5a8Q1W6sQc8W6a4lV2Y5h15k1F64k5F64k5F64k5F6A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard-1.0.0.min.js" integrity="sha512-WfASs5HtTgTL/eZsLaOftSN9wMQl7WZGlU5UiKx/yxTViMfGh9whWRwKAC27qH8VtZJqSMqDdbq2uUb1tY3jvQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

替换后可直接在全局使用Chess构造函数:

const game = new Chess();

内容的提问来源于stack exchange,提问作者Suvier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:31:58