打包后import.meta.url路径异常导致__path_cache失效的解决办法
解决Rollup打包后import.meta.url路径错误导致缓存路径失效的问题
方案1:通过查找项目根目录的package.json定位(最可靠)
这种方法不依赖打包配置,也不用环境变量,通过查找项目根的package.json确定正确的项目根路径,无论代码在开发目录还是打包后的目录都能正确计算:
- 安装支持ESM的文件查找库:
npm install find-up
- 修改
src/utils/index.ts代码:
import { findUpSync } from 'find-up'; import path from 'path'; import { fileURLToPath } from 'url'; // 从当前文件目录向上查找package.json,定位项目根目录 const packageJsonPath = findUpSync('package.json', { cwd: path.dirname(fileURLToPath(import.meta.url)) }); if (!packageJsonPath) { throw new Error('无法找到项目根目录的package.json'); } const __path_project_root = path.dirname(packageJsonPath); // 直接从项目根目录计算缓存路径 const __path_cache = path.resolve(__path_project_root, 'node_modules/.cache/@setup');
方案2:通过当前目录结构动态调整路径
无需额外依赖,通过判断当前文件所在目录的特征,动态调整向上跳转的层级:
修改src/utils/index.ts代码:
import path from 'path'; import { fileURLToPath } from 'url'; const currentDir = path.dirname(fileURLToPath(import.meta.url)); // 根据当前是否在src目录下,决定向上跳转的层级 const __path_project_root = currentDir.includes(path.sep + 'src' + path.sep) ? path.resolve(currentDir, '../../') // 开发环境:从src/utils跳两级到项目根 : path.resolve(currentDir, '../'); // 打包后:从dist跳一级到项目根 const __path_cache = path.resolve(__path_project_root, 'node_modules/.cache/@setup');
方案3:通过Rollup插件替换路径计算逻辑
利用Rollup的替换插件,在打包时自动将开发环境的路径计算替换为打包后的正确路径:
- 安装Rollup替换插件:
npm install @rollup/plugin-replace --save-dev
- 修改
rollup.config.js配置:
import replace from '@rollup/plugin-replace'; import path from 'path'; export default { // 你的其他Rollup配置(入口、输出格式等) plugins: [ replace({ preventAssignment: true, // 将开发环境的__path_src_root计算逻辑替换为项目根路径 values: { 'path.resolve(path.dirname(fileURLToPath(import.meta.url)), \'../\')': JSON.stringify(path.resolve(__dirname, './')) } }) ] };
- 调整
src/utils/index.ts中的缓存路径计算:
import path from 'path'; import { fileURLToPath } from 'url'; const __path_src_root = path.resolve( path.dirname(fileURLToPath(import.meta.url)), '../', ); // 去掉多余的../,统一从__path_src_root计算缓存路径 const __path_cache = path.resolve( __path_src_root, 'node_modules/.cache/@setup', );
内容的提问来源于stack exchange,提问作者NoraH1to
相关产品推荐
相关产品推荐

