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

feat: support npm alias name for prebundle #663

Merged
merged 5 commits into from
Jun 14, 2023
Merged
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
10 changes: 5 additions & 5 deletions src/doctor/rules/CJS_IMPORT_ESM.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { IApi } from '../../types';
import vm from 'vm';
import { chalk, winPath } from '@umijs/utils';
import type { IDoctorReport } from '..';
import { getPkgNameFromPath } from '../utils';
import enhancedResolve from 'enhanced-resolve';
import vm from 'vm';
import type { IDoctorReport } from '..';
import type { IApi } from '../../types';
import { getPkgNameFromPath } from '../../utils';

export default (api: IApi) => {
const sandbox = vm.createContext({ require });
let resolver: ReturnType<typeof enhancedResolve['create']['sync']>;
let resolver: ReturnType<(typeof enhancedResolve)['create']['sync']>;

api.describe({
// disable temporarily
Expand Down
2 changes: 1 addition & 1 deletion src/doctor/rules/PHANTOM_DEPS.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { chalk } from '@umijs/utils';
import type { IDoctorReport } from '..';
import type { IApi } from '../../types';
import { getPkgNameFromPath } from '../utils';
import { getPkgNameFromPath } from '../../utils';

export default (api: IApi) => {
api.addImportsCheckup(({ file, imports, mergedAlias, mergedExternals }) => {
Expand Down
3 changes: 0 additions & 3 deletions src/doctor/utils.ts

This file was deleted.

8 changes: 5 additions & 3 deletions src/prebundler/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { winPath } from '@umijs/utils';
import path from 'path';
import { IApi, IFatherPreBundleConfig } from '../types';
import {
getDepPkgName,
getDepPkgPath,
getDtsInfoForPkgPath,
getNestedTypeDepsForPkg,
Expand Down Expand Up @@ -127,14 +128,15 @@ export function getConfig(opts: {
// process deps config
Object.entries(deps).forEach(([dep, depConfig]) => {
// handle array deps
const depName = Array.isArray(deps) ? deps[parseInt(dep)] : dep;
let depName = Array.isArray(deps) ? deps[parseInt(dep)] : dep;
depConfig = Array.isArray(deps) ? {} : depConfig;

const depEntryPath = require.resolve(depName, { paths: [opts.cwd] });
const depPkgPath = getDepPkgPath(depName, opts.cwd);
const depTypeInfo =
depConfig.dts !== false ? getDtsInfoForPkgPath(depPkgPath) : null;
const depPkg = require(depPkgPath);
depName = getDepPkgName(depName, depPkg);

// generate bundle config
config.deps[depEntryPath] = {
Expand All @@ -147,7 +149,7 @@ export function getConfig(opts: {
pkg: depPkg,
output: path.resolve(
opts.cwd,
`${output || DEFAULT_OUTPUT_DIR}/${depPkg.name}/index.js`,
`${output || DEFAULT_OUTPUT_DIR}/${depName}/index.js`,
Copy link
Member

Choose a reason for hiding this comment

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

直接使用用户的配置值可能会存在 Breaking Change,目前想到这两种 case:

  1. 配置值可能是 NPM 包的文件路径(类似 pkg/lib/other
  2. 配置值可能是项目的本地文件(类似 Umi 仓库中 bundler-utils 子包的情况,虽然没有直接使用 father)

想到的解法你看看是否合适,创建 getDepPkgName(depName, depPkg) 的工具方法,有两层逻辑:

  1. 如果 depName 不是绝对路径或 . 开头的相对路径,则尝试截取 depName 中包名的部分,比如 pkg/lib/other => pkg@org/pkg/index => @org/pkg
  2. 反之兜底到 depPkg.name,同时需要看下 issue 里提到的 minimatch 获取 pkg 失败的问题,按理说 getDepPkg 有使用 pkgUp 处理,应该能拿到才是

Copy link
Contributor Author

Choose a reason for hiding this comment

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

很好我处理下,我没留意还有其他用法

),
};

Expand All @@ -167,7 +169,7 @@ export function getConfig(opts: {
}

// prepare deps externals
depExternals[depPkg.name] = config.deps[depEntryPath].output;
depExternals[depName] = config.deps[depEntryPath].output;
});

// process extraDtsDeps config
Expand Down
21 changes: 18 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { pkgUp, chalk, logger as umiLogger } from '@umijs/utils';
import { chalk, logger as umiLogger, pkgUp } from '@umijs/utils';
import Cache from 'file-system-cache';
import path from 'path';
import path, { isAbsolute } from 'path';
import { CACHE_PATH } from './constants';
import { IApi } from './types';

Expand All @@ -9,7 +9,7 @@ const caches: Record<string, ReturnType<typeof Cache>> = {};
/**
* get file-system cache for specific namespace
*/
export function getCache(ns: string): typeof caches['0'] {
export function getCache(ns: string): (typeof caches)['0'] {
// return fake cache if cache disabled
if (process.env.FATHER_CACHE === 'none') {
return { set() {}, get() {}, setSync() {}, getSync() {} } as any;
Expand Down Expand Up @@ -183,3 +183,18 @@ export const logger: Omit<IFatherLogger, '_quiet'> = new Proxy<IFatherLogger>(
},
},
);

export function isFilePath(path: string) {
return isAbsolute(path) || path.startsWith('.');
}

export function getPkgNameFromPath(p: string) {
return p.match(/^(?:@[a-z\d][\w-.]*\/)?[a-z\d][\w-.]*/i)?.[0];
}

export const getDepPkgName = (name: string, packageJson: { name: string }) => {
if (isFilePath(name)) {
return packageJson.name;
}
return getPkgNameFromPath(name) ?? name;
};
5 changes: 5 additions & 0 deletions tests/fixtures/prebundle/npm-alias/.fatherrc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
prebundle: {
deps: ['a', 'a-alias'],
},
};
12 changes: 12 additions & 0 deletions tests/fixtures/prebundle/npm-alias/expect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default (files: Record<string, string>) => {
expect(Object.keys(files)).toMatchInlineSnapshot(`
Array [
"a/index.d.ts",
"a/index.js",
"a/package.json",
"a-alias/index.d.ts",
"a-alias/index.js",
"a-alias/package.json",
]
`);
};

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions tests/fixtures/prebundle/npm-alias/node_modules/a/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions tests/fixtures/prebundle/npm-alias/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "npm-alias",
"version": "0.0.0",
"devDependencies": {
"a": "0.0.1",
"a-alias": "npm:[email protected]"
}
}
41 changes: 40 additions & 1 deletion tests/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { logger } from '../src/utils';
import { logger as umiLogger } from '@umijs/utils';
import { getDepPkgName, isFilePath, logger } from '../src/utils';

jest.mock('@umijs/utils', () => {
const originalModule = jest.requireActual('@umijs/utils');
Expand Down Expand Up @@ -55,4 +55,43 @@ describe('logger', () => {

process.env.NODE_ENV = originalEnv;
});

describe(isFilePath.name, () => {
test('absolute', () => {
expect(isFilePath('/path/to/name')).toBe(true);
});

test('relative', () => {
expect(isFilePath('./name/test')).toBe(true);
});

test('module', () => {
expect(isFilePath('name')).toBe(false);
expect(isFilePath('@scope/name')).toBe(false);
});
});

describe(getDepPkgName.name, () => {
test('normal module', () => {
expect(getDepPkgName('name', { name: 'test' })).toBe('name');
expect(getDepPkgName('name/test', { name: 'test' })).toBe('name');
});

test('scope module', () => {
expect(getDepPkgName('@scope/name', { name: 'test' })).toBe(
'@scope/name',
);
expect(getDepPkgName('@scope/name/test', { name: 'test' })).toBe(
'@scope/name',
);
});

test('absolute', () => {
expect(getDepPkgName('/path/to/name', { name: 'test' })).toBe('test');
});

test('relative', () => {
expect(getDepPkgName('./name/test', { name: 'test' })).toBe('test');
});
});
});