From 5a8a3ab5af24ef924958df36d9a41a8c5c009b76 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 15 Jul 2022 23:56:36 +0800 Subject: [PATCH] fix: externalize workspace relative import when bundle config (#9140) --- packages/vite/src/node/config.ts | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 28fe2cdebb8e58..6b9195f17927ed 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -900,13 +900,40 @@ async function bundleConfigFile( { name: 'externalize-deps', setup(build) { - build.onResolve({ filter: /.*/ }, (args) => { - const id = args.path + build.onResolve({ filter: /.*/ }, ({ path: id, importer }) => { + // externalize bare imports if (id[0] !== '.' && !path.isAbsolute(id)) { return { external: true } } + // bundle the rest and make sure that the we can also access + // it's third-party dependencies. externalize if not. + // monorepo/ + // ├─ package.json + // ├─ utils.js -----------> bundle (share same node_modules) + // ├─ vite-project/ + // │ ├─ vite.config.js --> entry + // │ ├─ package.json + // ├─ foo-project/ + // │ ├─ utils.js --------> external (has own node_modules) + // │ ├─ package.json + const idFsPath = path.resolve(path.dirname(importer), id) + const idPkgPath = lookupFile(idFsPath, [`package.json`], { + pathOnly: true + }) + if (idPkgPath) { + const idPkgDir = path.dirname(idPkgPath) + // if this file needs to go up one or more directory to reach the vite config, + // that means it has it's own node_modules (e.g. foo-project) + if (path.relative(idPkgDir, fileName).startsWith('..')) { + return { + // normalize actual import after bundled as a single vite config + path: idFsPath, + external: true + } + } + } }) } },