如何在 monorepo 中实时重新加载本地 npm 包?

问题描述 投票:0回答:1

我正在为 Vue 3(vite + ts)、云函数和共享库(共享函数和 ts 接口等)设置一个 monorepo 工作区。

我可以导入本地共享库文件夹来工作。我通过在我的共享库上执行 npm run build -- -- watch 来在我的前端项目中进行实时类型检查。

但由于某种原因,除非我卸载然后安装共享库包,否则转换为 Javascript 的所有内容都不会更新。

例如:在共享库中创建 const 并不能使其在我导入共享库的前端/后端项目中可用。但是创建一个界面,IS。

我尝试了一些方法并在互联网上搜索了很大一部分😂。 我尝试使用 vite.config,因为我认为它可能会对包进行某种缓存。

目前,我的 vite.config.ts 是这样的:

import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    host: true,
  },
  plugins: [vue()],
  resolve: {
    preserveSymlinks: true,
  },
  optimizeDeps: {
    include: ["shared-lib"],
  },
})

这是我的共享库中的index.ts:

// this is not usable / doesn't update live.
export const sharedConst = () => console.log("testing shared functionality")

// this updates live in other projects.
export interface TestInterface {
  name: {
    firstName: string
    lastName: string
  }
}

这就是我的 package.json 依赖项在前端的样子:

  "dependencies": {
    ...

    "shared-lib": "file:../backend/functions/dist/shared-lib"
  },

我将shared-lib构建到我的云函数的dist文件夹中,以便在上传时将其打包。 Vue/vite 并不关心它的包驻留在哪里。

typescript npm npm-scripts monorepo vite
1个回答
3
投票

不确定您是否仍然需要这个问题的答案,但几个小时后我已经设法让我的共享库适用于我的 Vue/Vite 项目。

我确保我的共享库是作为 ESM 而不是 CJS 构建的。

tsconfig.json:

{
    "compilerOptions": {
        "module": "ES2020",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true
        ...
    }
}

package.json:

{
    "type": "module"
    ...
}

然后您可以将模块添加到optimizeDeps.exclude,如下所述:https://vitejs.dev/config/server-options.html#server-watch。这可以防止共享库被预构建并且在不强制手动重建的情况下无法重建。

我已经设置了 vite.config.js 如下:

{
    server: {
        watch: {
            usePolling: true, // For Docker.
            ignored: ['!**/node_modules/shared-lib/**'],
        },
    },
    optimizeDeps: {
        exclude: ['shared-lib']
    },
    ...
}

为了让这个工作正常进行,将resolve.preserveSymlinks和server.watch.followSymlinks保留为默认值非常重要。

最后,在共享库上以监视模式(--watch)运行 tsc 非常重要,以确保源代码在编辑时得到重新编译:

使用此设置,我可以让我的 Vue/Vite 项目热重新加载对共享库的更改。

© www.soinside.com 2019 - 2024. All rights reserved.