Currently working on an Nx monorepo package-based React application that’s structured roughly as follows:
/apps/myApp
/package.json
/vite.config.ts (which extends root-level vite.config.ts file)
/libs
/myLib1
/package.json
/myLib2
/package.json
package.json
package-lock.json
vite.config.ts
Lets say the root-level package.json has a dependency on somePackage
v1.2.3 from npm
But myLib2
specifically needs v1.1.1
If I add these respective versions to the root-level package.json
and to the myLib2/package.json
files and run npm install
– I can see that somePackage
v1.2.3 gets installed to the root-level node_modules
folder and somePackage
v1.1.1 gets installed to the node_modules
folder inside myLib2
– which is what I would expect.
When running myApp (which has a dependency on myLib2
using Vite dev server – I am seeing code / components in myLib2
use v.1.2.3 of somePackage
when I want it to use v1.1.1.
When running Nx build – myLib2 correctly uses v1.1.1 – this issue is specific to Vite dev server.
When inspecting the code from Chrome Dev Tools – I can see that components inside myLib2
are indeed resolving myLib2
from the root-level node_modules
folder.
I’m thinking it’s somehow related to how Vite does dependency prebundling but I’m not quite sure how to resolve the issue.
Any help is much appreciated. Thanks!
Additional info:
vite: 4.3.4
nx: 16.2.2
Root-level vite.config.ts
:
/// <reference types="vitest" />
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import commonjs from 'vite-plugin-commonjs';
import viteTsConfigPaths from 'vite-tsconfig-paths';
import path from 'path';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, `${process.cwd()}/apps/myApp/env`, '');
return {
// vite config
cacheDir: '../../node_modules/.vite/myApp’,
build: {
commonjsOptions: {
include: [/myApp/, /node_modules/],
},
},
envDir: `${process.cwd()}/apps/myApp/env`,
esbuild: {
loader: 'tsx',
include: [
'apps/**/*.(ts|tsx|js|jsx)',
'libs/**/*.(ts|tsx|js|jsx)',
],
exclude: [],
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext',
loader: {
'.js': 'jsx',
'.ts': 'tsx',
},
},
},
server: {
port: 8080,
host: 'localhost',
fs: {
// Allow serving files from two levels up to the project root
allow: ['../..'],
},
},
preview: {
port: 8080,
},
plugins: [
react(),
commonjs({
}),
viteTsConfigPaths({
root: '../../',
}),
nodePolyfills({
include: ['util'],
globals: {
Buffer: true,
},
}),
],
};
});