Skip to content

Commit

Permalink
fix!: use regexps to match dependency externals (#213)
Browse files Browse the repository at this point in the history
* avoids inlining subpaths or fully resolved paths
  • Loading branch information
danielroe authored Jul 9, 2021
1 parent a9031cd commit 58de5db
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
28 changes: 27 additions & 1 deletion src/core/build/rollup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { resolve } from 'upath'

import { Package } from '../package'
import { builtins, builtinsMap } from './builtins'
import { getRollupConfig } from './rollup'
import { getRollupConfig, regexpForPackage } from './rollup'
import { getNameFunction } from './utils'

const getFixturePath = (path: string) =>
Expand Down Expand Up @@ -68,3 +68,29 @@ describe('builtins', () => {
expect(Object.values(map)[0]).toBe(true)
})
})

describe('external matching', () => {
const pattern = regexpForPackage('@nuxt/utils')

it('should match package name', () => {
expect(pattern.test('@nuxt/utils')).toBeTruthy()
})

it('should match package subpath', () => {
expect(pattern.test('@nuxt/utils/subpath')).toBeTruthy()
})

it('should match fully resolved package path', () => {
expect(
pattern.test('/project/node_modules/@nuxt/utils/index.js')
).toBeTruthy()
expect(
pattern.test('c:\\project\\node_modules\\@nuxt\\utils\\index.js')
).toBeTruthy()
})

it('should not match substring paths', () => {
expect(pattern.test('@nuxt/utils2')).toBeFalsy()
expect(pattern.test('a@nuxt/utils')).toBeFalsy()
})
})
17 changes: 14 additions & 3 deletions src/core/build/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ export interface BuildOverride {
format: OutputOptions['format']
}

export function regexpForPackage(name: string) {
// Should match `@foo/bar/index.js`, `node_modules\@foo\bar`,
// `node_modules/@foo/bar` as well as `@foo/bar`.
name = name.replace(/[\\/]/g, '[\\\\/]')
return new RegExp(`(^|node_modules[\\\\/])${name}([\\\\/]|$)`, 'i')
}

function regexpForPackages(packages?: Record<string, string>) {
return Object.keys(packages || {}).map(regexpForPackage)
}

export function getRollupConfig(
{
input,
Expand Down Expand Up @@ -74,9 +85,9 @@ export function getRollupConfig(

const external = [
// Dependencies that will be installed alongside the package
...Object.keys(pkgConfig.dependencies || {}),
...Object.keys(pkgConfig.optionalDependencies || {}),
...Object.keys(pkgConfig.peerDependencies || {}),
...regexpForPackages(pkgConfig.dependencies),
...regexpForPackages(pkgConfig.optionalDependencies),
...regexpForPackages(pkgConfig.peerDependencies),
// Builtin node modules
...builtins,
...externals,
Expand Down

0 comments on commit 58de5db

Please sign in to comment.