Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: try to find shared package.json #216

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions src/plugins/pluginProxySharedModule_preBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ export function proxySharedModule(options: {
config(config: UserConfig, { command }) {
(config.resolve as any).alias.push(
...Object.keys(shared).map((key) => {
const pattern = key.endsWith('/')
? `(^${key.replace(/\/$/, '')}(\/.+)?$)`
: `(^${key}$)`;
const pattern = key.endsWith('/') ? `(^${key.replace(/\/$/, '')}(\/)?$)` : `(^${key}$)`;
return {
// Intercept all shared requests and proxy them to loadShare
find: new RegExp(pattern),
Expand Down
41 changes: 26 additions & 15 deletions src/utils/normalizeModuleFederationOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type RemoteEntryType =
| 'system'
| string;

import { existsSync } from 'fs';
import * as path from 'pathe';
import { warn } from './logUtils';

Expand Down Expand Up @@ -106,15 +107,26 @@ export interface ShareItem {
shareConfig: SharedConfig;
}

function removePathFromNpmPackage(packageString: string): string {
// 匹配npm包名的正则表达式,忽略路径部分
const regex = /^(?:@[^/]+\/)?[^/]+/;
function cleanShareItem(key: string) {
return key.replace(/^\//, '').replace(/\/$/, '');
}

function findPackageJson(moduleName: string) {
const mainFilePath = require.resolve(moduleName);

// 使用正则表达式匹配并提取包名
const match = packageString.match(regex);
let currentDir = path.dirname(mainFilePath);
while (
path.parse(currentDir).base !== 'node_modules' &&
currentDir !== path.parse(currentDir).root
) {
const potentialPackageJsonPath = path.join(currentDir, 'package.json');
if (existsSync(potentialPackageJsonPath)) {
return require(potentialPackageJsonPath);
}
currentDir = path.dirname(currentDir);
}

// 返回匹配到的包名,如果没有匹配到则返回原字符串
return match ? match[0] : packageString;
throw new Error(`Unable to find package.json for the module "${moduleName}"`);
Copy link
Collaborator

@gioboa gioboa Dec 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like it @nicotu01 👍
A good error message is always valuable

}

function normalizeShareItem(
Expand All @@ -131,14 +143,15 @@ function normalizeShareItem(
}
): ShareItem {
let version: string | undefined;
const shareName = cleanShareItem(key);
try {
version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
version = findPackageJson(shareName).version;
} catch (e) {
console.log(e);
}
if (typeof shareItem === 'string') {
return {
name: shareItem,
name: shareName,
version,
scope: 'default',
from: '',
Expand All @@ -149,7 +162,7 @@ function normalizeShareItem(
};
}
return {
name: key,
name: shareName,
from: '',
version: shareItem.version || version,
scope: shareItem.shareScope || 'default',
Expand Down Expand Up @@ -182,13 +195,13 @@ function normalizeShared(
const result: NormalizedShared = {};
if (Array.isArray(shared)) {
shared.forEach((key) => {
result[key] = normalizeShareItem(key, key);
result[cleanShareItem(key)] = normalizeShareItem(key, key);
});
return result;
}
if (typeof shared === 'object') {
Object.keys(shared).forEach((key) => {
result[key] = normalizeShareItem(key, shared[key] as any);
result[cleanShareItem(key)] = normalizeShareItem(key, shared[key] as any);
});
}

Expand Down Expand Up @@ -313,9 +326,7 @@ export function getNormalizeModuleFederationOptions() {

export function getNormalizeShareItem(key: string) {
const options = getNormalizeModuleFederationOptions();
const shareItem =
options.shared[removePathFromNpmPackage(key)] ||
options.shared[removePathFromNpmPackage(key) + '/'];
const shareItem = options.shared[cleanShareItem(key)];
return shareItem;
}

Expand Down
Loading