Skip to content

Commit

Permalink
feat: support npm alias name for prebundle (#663)
Browse files Browse the repository at this point in the history
* feat: support alias name

* feat: support

* feat: confirm file path

* feat: reuse

* chore: remove useless file

---------

Co-authored-by: Peach <scdzwyxst@gmail.com>
  • Loading branch information
Dunqing and PeachScript committed Jun 14, 2023
1 parent ef8a288 commit 8df2e42
Show file tree
Hide file tree
Showing 15 changed files with 114 additions and 16 deletions.
10 changes: 5 additions & 5 deletions src/doctor/rules/CJS_IMPORT_ESM.ts
@@ -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
@@ -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
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`,
),
};

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
@@ -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
@@ -0,0 +1,5 @@
export default {
prebundle: {
deps: ['a', 'a-alias'],
},
};
12 changes: 12 additions & 0 deletions tests/fixtures/prebundle/npm-alias/expect.ts
@@ -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
@@ -0,0 +1,8 @@
{
"name": "npm-alias",
"version": "0.0.0",
"devDependencies": {
"a": "0.0.1",
"a-alias": "npm:a@0.0.1"
}
}
41 changes: 40 additions & 1 deletion tests/utils.test.ts
@@ -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');
});
});
});

0 comments on commit 8df2e42

Please sign in to comment.