From 42508429568044c7db554b2f3f01cfc77a6dc746 Mon Sep 17 00:00:00 2001 From: saltysugar <49533754+saltysugar@users.noreply.github.com> Date: Tue, 20 Aug 2019 16:52:33 +0800 Subject: [PATCH] fix: fix scoped package support (#362) * fix scoped package * Update jsdoc --- .../lib/utils/__test__/resolvePackage.test.js | 18 ++++++++++ packages/saber/lib/utils/resolvePackage.js | 34 +++++++++++++------ 2 files changed, 42 insertions(+), 10 deletions(-) create mode 100644 packages/saber/lib/utils/__test__/resolvePackage.test.js diff --git a/packages/saber/lib/utils/__test__/resolvePackage.test.js b/packages/saber/lib/utils/__test__/resolvePackage.test.js new file mode 100644 index 000000000..020b37bc6 --- /dev/null +++ b/packages/saber/lib/utils/__test__/resolvePackage.test.js @@ -0,0 +1,18 @@ +const resolvePackage = require('../resolvePackage') + +test('resolvePackage', () => { + expect(resolvePackage('foo', { cwd: false })).toBe('foo') + expect(resolvePackage('@foo/bar', { cwd: false })).toBe('@foo/bar') + expect(resolvePackage('foo', { prefix: 'prefix-', cwd: false })).toBe( + 'prefix-foo' + ) + expect(resolvePackage('prefix-foo', { prefix: 'prefix-', cwd: false })).toBe( + 'prefix-foo' + ) + expect(resolvePackage('@foo/bar', { prefix: 'prefix-', cwd: false })).toBe( + '@foo/prefix-bar' + ) + expect( + resolvePackage('@foo/prefix-bar', { prefix: 'prefix-', cwd: false }) + ).toBe('@foo/prefix-bar') +}) diff --git a/packages/saber/lib/utils/resolvePackage.js b/packages/saber/lib/utils/resolvePackage.js index badcf81a2..0b7f65d83 100644 --- a/packages/saber/lib/utils/resolvePackage.js +++ b/packages/saber/lib/utils/resolvePackage.js @@ -4,23 +4,37 @@ const resolveFrom = require('resolve-from') const LOCAL_PATH_RE = /^[./]|(^[a-zA-Z]:)/ +/** + * Add prefix to package name + * @param {string} input + * @param {string=} prefix + */ +const addPrefix = (input, prefix) => { + if (!prefix) return input + + if (input.startsWith('@')) { + return input.replace(new RegExp(`^@(\\w+)/(${prefix})?`), `@$1/${prefix}`) + } + + return input.startsWith(prefix) ? input : `${prefix}${input}` +} + /** * @param {string} input * @param {Object} options - * @param {string} [options.cwd=process.cwd()] + * @param {string|false} [options.cwd=process.cwd()] * @param {string=} options.prefix */ module.exports = (input, { cwd = process.cwd(), prefix } = {}) => { if (LOCAL_PATH_RE.test(input)) { - return path.resolve(cwd, input) + return cwd === false ? input : path.resolve(cwd, input) + } + + input = addPrefix(input, prefix) + + if (cwd === false) { + return input } - return path.dirname( - resolveFrom( - cwd, - `${ - !prefix || input.startsWith(prefix) ? input : `${prefix}${input}` - }/package.json` - ) - ) + return path.dirname(resolveFrom(cwd, `${input}/package.json`)) }