使用 pnpm 的 TypeScript + SvelteKit monorepo 出现“ReferenceError:未定义导出”

Ada*_*tle 8 typescript monorepo vite sveltekit

我正在尝试围绕我的 SvelteKit 应用程序构建一个 monorepo,其中该应用程序和各种 monorepo 包都是用 TypeScript 编写的。

SvelteKit 应用程序工作正常,直到我尝试从 monorepo 中将符号链接到一个特定包中。问题包取决于@redis/client(我希望它非常可靠)并且错误消息引用该模块:

ReferenceError:导出未 在 /@fs/Users/me/project/node_modules/.pnpm/@redis+client@1.5.6/node_modules/@redis/client/dist/index.js:16:23 在 instantiateModule 处定义(文件:///Users/me/project/node_modules/.pnpm/vite@4.1.4/node_modules/vite/dist/node/chunks/dep-ca21228b.js:52420:15)

如果我将 monorepo 包发布到我们的私有 github 包注册表,并从那里安装它们,它就可以正常工作...所以我认为我构建 TS 包的方式是可以的...但作为参考,这里是依赖于以下包的 package.json 的片段@redis/client

"type": "module",
"types": "dist/index.d.ts",
"exports": {
    "import": "./dist/index.js",
    "require": "./dist/index.cjs"
},
Run Code Online (Sandbox Code Playgroud)

以及来自同一包的 tsconfig:

{
    "compilerOptions": {
        "target": "es6", //also tried ES2022
        "module": "commonjs", //also tried ES2022
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true,
        "noUncheckedIndexedAccess": true,
        "noEmit": true,
        "moduleResolution": "node"
    }
}
Run Code Online (Sandbox Code Playgroud)

SvelteKit 应用程序通常包含type=module在其 package.json 中,并使用 Vite。vite 配置非常普通:

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

export default defineConfig({
    plugins: [sveltekit()],
    test: {
        include: ['src/**/*.{test,spec}.{js,ts}']
    }
});
Run Code Online (Sandbox Code Playgroud)

它确实使用了稍微不同的 tsconfig,它是由 SvelteKit 新应用程序向导为我生成的:

{
    "extends": "./.svelte-kit/tsconfig.json",
    "compilerOptions": {
        "allowJs": true,
        "checkJs": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "resolveJsonModule": true,
        "skipLibCheck": true,
        "sourceMap": true,
        "strict": true,
        "ignoreDeprecations": "5.0"
    }
}
Run Code Online (Sandbox Code Playgroud)

由于如果将包发布到私有包存储库并像往常一样使用 pnpm 安装,它就可以工作,所以我不得不相信这是某种 Vite 配置问题。

根据不和谐服务器中某人的建议,我尝试了我能想到的所有排列来获取Vite 配置optimizeDeps.include和/或build.commonjsOptions.include设置来解决此问题;但我没有看到任何变化。我什至不确定这是否是对的。

我在这里创建了尽可能小的复制案例,包括我创建复制品所采取的步骤列表,按照我采取的顺序排列。

如果您正在查看重现代码并问自己为什么我想像这样包装@redis/client,答案就在我出于商业原因、重现简洁性等而省略的所有内容中。我保证你需要这样做;但 tl;dr 是,getRedis实际项目中的方法接受一些参数,这些参数定义我们想要将 redis 客户端连接到什么环境和什么客户(例如 ABC、生产),并且它会查找正确的配置并返回连接的客户端。

Tom*_*cik 2

看起来这可能与如何处理Vite由.生成的符号链接有关pnpm。显然将您的配置更改为:

export default defineConfig({
    plugins: [sveltekit()],
    resolve: {
        preserveSymlinks: true,
    },
});
Run Code Online (Sandbox Code Playgroud)

根据https://v2.vitejs.dev/config/#resolve-preservesymlinks解析Internal server error: exports is not defined. 我仍然得到Error: The client is closed,但我想这是预期的行为。