Skip to content

Commit

Permalink
feat: try resolving paths as npm package
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jun 29, 2022
1 parent f6506e8 commit 7c48947
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/loader.ts
Expand Up @@ -153,15 +153,21 @@ async function extendConfig (config, opts: LoadConfigOptions) {

const GIT_PREFIXES = ['github:', 'gitlab:', 'bitbucket:', 'https://']

// https://github.com/dword-design/package-name-regex
const NPM_PACKAGE_RE = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/

const jiti = createJiti(null, { cache: false, interopDefault: true, requireCache: false })

async function resolveConfig (source: string, opts: LoadConfigOptions): Promise<ResolvedConfig> {
// Custom user resolver
if (opts.resolve) {
const res = await opts.resolve(source, opts)
if (res) {
return res
}
}

// Download git URLs and resolve to local path
if (GIT_PREFIXES.some(prefix => source.startsWith(prefix))) {
const url = new URL(source)
const subPath = url.pathname.split('/').slice(2).join('/')
Expand All @@ -173,6 +179,15 @@ async function resolveConfig (source: string, opts: LoadConfigOptions): Promise<
await gittar.extract(tarFile, tmpdir)
source = resolve(tmpdir, subPath)
}

// Try resolving as npm package
if (NPM_PACKAGE_RE.test(source)) {
try {
source = jiti.resolve(source, { paths: [opts.cwd] })
} catch (_err) {}
}

// Import from local fs
const isDir = !extname(source)
const cwd = resolve(opts.cwd, isDir ? source : dirname(source))
if (isDir) { source = opts.configFile }
Expand Down
1 change: 1 addition & 0 deletions test/fixture/.gitignore
@@ -0,0 +1 @@
!node_modules
3 changes: 3 additions & 0 deletions test/fixture/node_modules/c12-npm-test/config.ts

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

7 changes: 7 additions & 0 deletions test/fixture/node_modules/c12-npm-test/package.json

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

8 changes: 8 additions & 0 deletions test/index.test.ts
Expand Up @@ -40,6 +40,7 @@ describe('c12', () => {
"configFile": true,
"defaultConfig": true,
"devConfig": true,
"npmConfig": true,
"overriden": true,
"rcFile": true,
"virtual": true,
Expand Down Expand Up @@ -117,6 +118,13 @@ describe('c12', () => {
"configFile": "<path>/fixture/config.dev.ts",
"cwd": "<path>/fixture",
},
{
"config": {
"npmConfig": true,
},
"configFile": "<path>/fixture/node_modules/c12-npm-test/config.ts",
"cwd": "<path>/fixture/node_modules/c12-npm-test",
},
]
`)
})
Expand Down

0 comments on commit 7c48947

Please sign in to comment.