Vite SSR报错:exports is not defined(Webpack迁移至Vite问题)
解决Vite SSR迁移时的
exports is not defined报错 针对你从Webpack迁移到Vite后SSR出现的ReferenceError: exports is not defined问题,核心原因是CommonJS与ES模块的转译兼容问题,尤其是isomorphicSecrets包(或文件)的格式与Vite SSR的模块处理逻辑不匹配,以下是具体解决方案:
1. 调整Vite配置,强制转译目标依赖
修改vite.config.ts,添加SSR相关配置并优化插件顺序:
import { defineConfig } from 'vite' import { VitePluginNode } from 'vite-plugin-node' import commonjs from 'vite-plugin-commonjs' export default defineConfig({ server: { port: 3001, }, build: { target: 'esnext', commonjsOptions: { transformMixedEsModules: true } }, // 强制Vite转译指定的CommonJS依赖,避免模块格式冲突 ssr: { noExternal: ['isomorphicSecrets'] }, plugins: [ // 先加载VitePluginNode初始化SSR环境,再处理CommonJS转译 ...VitePluginNode({ adapter: 'express', appPath: 'some/path/server', exportName: 'app', tsCompiler: 'esbuild', }), // 仅针对目标依赖进行CommonJS转译,减少全局干扰 commonjs({ include: [/node_modules\/isomorphicSecrets/] }) ], })
2. 修正TypeScript配置,适配Vite模块系统
修改tsconfig.json,使用Vite推荐的ES模块配置:
{ "compilerOptions": { "target": "esnext", "module": "esnext", // 改为ES模块格式,匹配Vite的处理逻辑 "lib": ["es7", "es2015", "es2017", "dom", "esnext"], "moduleResolution": "bundler", // 使用Vite原生的模块解析规则 "esModuleInterop": true, "skipLibCheck": true // 跳过库类型检查,加快编译速度 } }
3. 移除不必要的Babel插件
Vite默认使用esbuild处理代码转译,额外的vite-plugin-babel可能与现有转译逻辑冲突,直接从插件列表中移除即可。
额外排查点
如果isomorphicSecrets是你自己编写的文件,检查其导出格式:
- 确保使用ES模块语法(
export/export default),而非CommonJS的module.exports/exports。 - 若必须保留CommonJS格式,调整
commonjs插件的include规则,覆盖该文件路径。
内容的提问来源于stack exchange,提问作者noblerare
相关产品推荐
相关产品推荐

