fix: 使用 pathToFileURL 确保 Windows 下路径导入正确

修改多处文件导入逻辑,统一使用 pathToFileURL 转换路径为 URL 格式,解决 Windows 系统下路径格式问题导致的模块导入失败
This commit is contained in:
wanchun 2025-09-07 16:48:28 +08:00
parent 2c69c96642
commit ed26dfb39b
3 changed files with 12 additions and 3 deletions

View File

@ -3,6 +3,7 @@ import assert from 'node:assert';
import { existsSync } from 'node:fs';
import { extname, join } from 'node:path';
import process from 'node:process';
import { pathToFileURL } from 'node:url';
import { chalk, chokidar, compatESModuleRequire, deepmerge, lodash, winPath } from '@fesjs/utils';
import joi from 'joi';
import { ServiceStage } from '../service/enums';
@ -141,7 +142,11 @@ export default class Config {
}
async requireConfigs(configFiles: string[]): Promise<any[]> {
const models = await Promise.all(configFiles.map(f => import(f)));
const models = await Promise.all(configFiles.map(f => {
// 使用 pathToFileURL 确保在 Windows 下路径格式正确
const fileUrl = pathToFileURL(f).href;
return import(fileUrl);
}));
return models.map(m => compatESModuleRequire(m));
}

View File

@ -1,6 +1,7 @@
import type { Plugin } from '../../types';
import { basename, dirname, extname, join, relative } from 'node:path';
import process from 'node:process';
import { pathToFileURL } from 'node:url';
import { chalk, compatESModuleRequire, lodash, resolve, winPath } from '@fesjs/utils';
import { readJSONSync } from 'fs-extra/esm';
import { packageUp } from 'package-up';
@ -158,7 +159,9 @@ export async function pathToObj({ path, type, cwd }: PathToObjOptions): Promise<
path: winPath(path),
async apply() {
try {
const ret = await import(path);
// 使用 pathToFileURL 确保在 Windows 下路径格式正确
const fileUrl = pathToFileURL(path).href;
const ret = await import(fileUrl);
// use the default member for es modules
return compatESModuleRequire(ret);
}

View File

@ -1,6 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import process from 'node:process';
import { pathToFileURL } from 'node:url';
import { chokidar, lodash } from '@fesjs/utils';
export default (api) => {
@ -100,7 +101,7 @@ export default (api) => {
// require最新的 mock.js 文件
try {
// register babel
const _initFunction = await import(mockFile);
const _initFunction = await import(pathToFileURL(mockFile).href);
const initFunction = _initFunction.default || _initFunction;
if (!lodash.isFunction(initFunction)) {
api.logger.info('mock.js should export Function');