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

TypeScript+SvelteKit+pnpm monorepo中exports未定义错误排查

解决方案

1. 修正内部包的TypeScript编译配置

原内部包tsconfig.json中noEmit: true会导致无法生成编译后的文件,本地链接时Vite可能直接处理源码引发依赖解析错误。修改配置如下:

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "ESNext",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true,
        "noUncheckedIndexedAccess": true,
        "moduleResolution": "node",
        "outDir": "./dist",
        "declaration": true,
        "declarationDir": "./dist"
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}

同时在内部包package.json添加构建脚本:

"scripts": {
    "build": "tsc"
}

执行pnpm run build生成正确的ESM格式文件后再重新链接。

2. 强制Vite转换@redis/client为ESM格式

在SvelteKit的vite.config.ts中添加ESBuild插件,将CommonJS格式的@redis/client转换为ESM:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';

export default defineConfig({
    plugins: [sveltekit()],
    optimizeDeps: {
        esbuildOptions: {
            target: 'es2020',
            plugins: [
                {
                    name: 'redis-client-esm-adapter',
                    setup(build) {
                        build.onResolve({ filter: /@redis\/client/ }, args => ({
                            path: args.path,
                            namespace: 'redis-cjs'
                        }));
                        build.onLoad({ filter: /.*/, namespace: 'redis-cjs' }, async args => {
                            const fs = require('fs');
                            const path = require('path');
                            const filePath = require.resolve(args.path);
                            let content = fs.readFileSync(filePath, 'utf8');
                            
                            // 转换CommonJS导出为ESM格式
                            content = content.replace(/module.exports = /g, 'export default ')
                                .replace(/exports\.(\w+) = /g, 'export const $1 = ');
                            
                            return { contents: content, loader: 'js' };
                        });
                    }
                }
            ]
        }
    },
    test: {
        include: ['src/**/*.{test,spec}.{js,ts}']
    }
});

3. 配置SSR不外部化依赖(若使用SSR)

如果应用启用了SSR,将内部包和@redis/client设为不外部化,确保Vite构建时完整处理它们:

export default defineConfig({
    // ...其他配置
    ssr: {
        noExternal: ['@your-internal-package-name', '@redis/client']
    }
});

4. 重新建立pnpm链接

执行以下命令确保依赖链接正确:

pnpm install
pnpm run build --filter @your-internal-package-name
pnpm link --filter @your-sveltekit-app-name @your-internal-package-name

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:25:00