Vite开发版本正常,生产构建版本出现wikibase-sdk初始化错误
Vite构建生产版本出现
ReferenceError: can't access lexical declaration 'simplifyEntities' before initialization问题排查与解决 问题描述
项目在Vite开发环境(执行vite命令)下运行正常,但执行tsc && vite build构建生产版本并启动服务器后,抛出以下错误:
Uncaught ReferenceError: can't access lexical declaration 'simplifyEntities' before initialization <anonymous> http://localhost:4173/assets/propertyEditor-b00fceb9.js:1075
环境与依赖信息
- wikibase-sdk 版本:^9.1.0
- 运行浏览器:Firefox / Chromium 最新版本
- 项目分支:dev
项目配置
项目脚本
"dev": "vite", "build:dev": "tsc && vite build",
Vite配置文件(vite.config.js)
export default { build: { outDir: "dist", emptyOutDir: true, minify: false, sourcemap: true, mode: "development", rollupOptions: { input: { home: "./index.html", visTest: "./src/pages/visTest/index.html", propertyEditor: "src/pages/propertyEditor/index.html", }, }, }, };
相关代码
业务调用代码(错误关联wikibase-sdk)
import { WBK } from "wikibase-sdk"; import type { SparqlResults } from "wikibase-sdk"; export default class QueryDispatcher { private readonly instance = "https://graphit.ur.de"; private readonly endpoint = "https://query.graphit.ur.de/proxy/wdqs/bigdata/namespace/wdq/sparql"; private readonly wbk = WBK({ sparqlEndpoint: this.endpoint, instance: this.instance, }); async query(sparql: string): Promise<SparqlResults> { const url = this.wbk.sparqlQuery(sparql); const headers = {}; const response = await fetch(url, { headers }); const data = await response.json(); return data; } }
执行的SPARQL查询语句
PREFIX wdt: <https://graphit.ur.de/prop/direct/> SELECT ?source ?sourceLabel ?sourceNodeClass ?sourceNodeClassLabel ?sourceNodeImage ?dependency ?dependencyLabel ?dependencyNodeClass ?dependencyNodeClassLabel ?dependencyNodeImage WHERE { ?source wdt:P1 ?dependency. ?source wdt:P2 ?sourceNodeClass. OPTIONAL { ?source wdt:P9 ?sourceNodeImage. } OPTIONAL { ?dependency wdt:P2 ?dependencyNodeClass. } OPTIONAL { ?dependency wdt:P9 ?dependencyNodeImage. } SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } }
核心疑问
项目使用Webpack构建可正常运行,仅Vite构建生产包后出现此错误,请问差异原因是什么?如何解决?
问题原因
该错误源于wikibase-sdk内部代码存在变量提升相关的不规范写法。Vite基于Rollup构建,生产模式下对ES模块的作用域处理更严格,当模块内let/const声明的变量在初始化前被引用时,会直接抛出错误;而Webpack的模块打包逻辑会对这类场景做兼容处理,因此不会触发报错。
解决方法
- 升级wikibase-sdk版本:该问题大概率已在后续版本中修复,尝试将依赖升级至最新稳定版,重新安装后再构建。
- 配置Vite预构建依赖:在vite.config.js中添加
optimizeDeps配置,强制预构建wikibase-sdk,避免Rollup打包时的作用域处理问题:
export default { // 原有build配置... optimizeDeps: { include: ['wikibase-sdk'] } };
- 切换CommonJS导入方式:若升级版本无效,可改用CommonJS格式导入,绕过ES模块的作用域校验:
const { WBK } = require("wikibase-sdk"); import type { SparqlResults } from "wikibase-sdk";
- 临时禁用Rollup TreeShaking:在Vite的build配置中关闭TreeShaking(会增加打包体积,仅作为临时方案):
export default { build: { // 原有配置... rollupOptions: { treeshake: false } } };
内容的提问来源于stack exchange,提问作者AlexW00
相关产品推荐
相关产品推荐

