You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite Library Mode在Windows与Linux下的构建差异及解决咨询

Vite Library Mode 跨平台构建结果不一致问题解决

问题场景

使用Vite Library Mode开发npm包,代码结构如下:

utilities.ts

export function thisGetsRemovedInBundle() {
  console.log('This should be in the bundle!');
}

export function thisIsUsed() {
  console.log('Used!');
  return 1;
}

components/index.ts

import { thisIsUsed } from '../utilities';

export default {
  Hello: thisIsUsed(),
};

vite.config.ts

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

export default defineConfig({
  plugins: [vue()],
  build: {
    lib: {
      entry: 'components/index.ts',
      formats: ['es'],
    },
    rollupOptions: {
      external: ['vue'],
      input: {
        index: 'components/index.ts',
        utilities: 'utilities.ts',
      },
      output: {
        dir: 'dist',
        format: 'es',
        entryFileNames: '[name].js',
      },
    },
  },
});

Windows 10环境构建后,dist/index.js将thisIsUsed函数直接内嵌,导致代码重复:

function thisIsUsed() {
  console.log("Used!");
  return 1;
}
var index = {
  Hello: thisIsUsed()
};
export { index as default };

Ubuntu环境构建结果符合预期,dist/index.js正确导入utilities模块:

import { thisIsUsed } from "./utilities.js";
var index = {
  Hello: thisIsUsed()
};
export { index as default };

需要实现Windows与Linux下一致的构建结果,避免代码重复。

问题原因

核心是跨平台路径大小写处理差异:Windows文件系统不区分路径大小写,而Linux严格区分。Rollup解析模块时,Windows环境下会把大小写不一致的路径视为不同模块,从而触发代码内嵌逻辑;Linux环境下则正确识别为同一模块,保留导入关系。

解决方法

1. 统一路径大小写

确保代码中的导入路径与vite.config.ts里rollupOptions.input配置的路径大小写完全一致。例如:

  • 若input配置为utilities: 'utilities.ts',则导入时写成import { thisIsUsed } from '../utilities.ts',或者统一文件名大小写(如全小写命名文件)。

2. 开启preserveModules配置

在Rollup的output选项中添加preserveModules: true,强制保留模块结构,避免Rollup将模块内容内嵌到其他文件:

// 修改vite.config.ts中的output配置
output: {
  dir: 'dist',
  format: 'es',
  entryFileNames: '[name].js',
  preserveModules: true // 新增配置
},

3. 调整TreeShake配置(备选)

若上述方法无效,可尝试调整Rollup的TreeShake规则,禁止模块合并行为(不推荐,会影响打包体积优化):

rollupOptions: {
  treeshake: {
    moduleSideEffects: false,
    propertyReadSideEffects: false,
    tryCatchDeoptimization: false
  },
  // 其他原有配置...
}

内容的提问来源于stack exchange,提问作者incutonez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:27:29