From a76919c5cd19278ee397e9438ec89b68d336a711 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Mon, 11 Oct 2021 20:13:54 -0400 Subject: [PATCH] fix: respect "sideEffects: true" in package.json We can assume a package has side effects in this case. This is basically a way to force Rollup to always include the package when imported. --- packages/vite/src/node/plugins/resolve.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 9b8519a43119c0..f58e0219fadf82 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -583,7 +583,7 @@ export function tryOptimizedResolve( export interface PackageData { dir: string - hasSideEffects: (id: string) => boolean + hasSideEffects: (id: string) => boolean | 'no-treeshake' webResolvedImports: Record nodeResolvedImports: Record setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void @@ -621,13 +621,19 @@ export function resolvePackageData( function loadPackageData(pkgPath: string, cacheKey = pkgPath) { const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) const pkgDir = path.dirname(pkgPath) + + // When the "sideEffects" field is defined, we can assume modules + // in the package are either side effect-free or not, which means + // Rollup doesn't have to statically analyze the AST. const { sideEffects } = data - let hasSideEffects: (id: string) => boolean + let hasSideEffects: (id: string) => boolean | 'no-treeshake' if (typeof sideEffects === 'boolean') { - hasSideEffects = () => sideEffects + hasSideEffects = () => sideEffects && 'no-treeshake' } else if (Array.isArray(sideEffects)) { - hasSideEffects = createFilter(sideEffects, null, { resolve: pkgDir }) + const filter = createFilter(sideEffects, null, { resolve: pkgDir }) + hasSideEffects = (id) => filter(id) && 'no-treeshake' } else { + // Statically analyze each module for side effects. hasSideEffects = () => true }