Vite开发服务器无法启动:Cannot redefine property: crypto错误求助
解决Vite开发服务器启动时的
Cannot redefine property: crypto错误 问题原因
这个报错是因为SvelteKit自带的Node环境polyfill和你安装的vite-plugin-node-polyfills插件产生了冲突——两者都尝试定义crypto属性,导致重复定义的类型错误。
解决方案
方案1:移除多余的polyfill插件(推荐)
SvelteKit已经为Node环境内置了必要的polyfill,不需要额外安装vite-plugin-node-polyfills。执行以下操作:
- 卸载插件:
npm uninstall vite-plugin-node-polyfills
- 修改
vite.config.js,移除插件相关代码,恢复为基础配置:
import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [sveltekit()] });
- 重新启动开发服务器:
npm run dev
方案2:保留插件但排除冲突的polyfill
如果你确实需要使用vite-plugin-node-polyfills处理其他Node模块,可以在配置中排除crypto,避免重复定义:
修改vite.config.js:
import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; import { nodePolyfills } from "vite-plugin-node-polyfills"; export default defineConfig({ plugins: [ sveltekit(), nodePolyfills({ protocolImports: true, // 排除crypto,避免与SvelteKit内置polyfill冲突 exclude: ['crypto'] }), ] });
之后重新启动开发服务器即可。
内容的提问来源于stack exchange,提问作者Player
相关产品推荐
相关产品推荐

