Skip to content

Commit 1b9159d

Browse files
committed
feat: support functional patterns
resolves #122
1 parent f5e6470 commit 1b9159d

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/index.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export interface ImpoundMatcherOptions {
1111
/** Whether to throw an error or not. if set to `false`, an error will be logged to console instead. */
1212
error?: boolean
1313
/** An array of patterns to prevent being imported, along with an optional warning to display. */
14-
patterns: [importPattern: string | RegExp, warning?: string][]
14+
patterns: [importPattern: string | RegExp | ((id: string) => boolean | string), warning?: string][]
1515
}
1616

1717
export interface ImpoundSharedOptions {
@@ -49,10 +49,15 @@ export const ImpoundPlugin = createUnplugin((globalOptions: ImpoundOptions) => {
4949

5050
const logError = options.error === false ? console.error : this.error.bind(this)
5151
for (const [pattern, warning] of options.patterns) {
52-
const usesImport = pattern instanceof RegExp ? pattern.test(id) : pattern === id
52+
const usesImport = pattern instanceof RegExp
53+
? pattern.test(id)
54+
: typeof pattern === 'string'
55+
? pattern === id
56+
: pattern(id)
57+
5358
if (usesImport) {
5459
const relativeImporter = isAbsolute(importer) && globalOptions.cwd ? relative(globalOptions.cwd, importer) : importer
55-
logError(`${warning || 'Invalid import'} [importing \`${id}\` from \`${relativeImporter}\`]`)
60+
logError(`${typeof usesImport === 'string' ? usesImport : (warning || 'Invalid import')} [importing \`${id}\` from \`${relativeImporter}\`]`)
5661
matched = true
5762
}
5863
}

test/index.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ describe('impound plugin', () => {
3232
expect(result.message).toMatchInlineSnapshot(`"[plugin impound] Invalid import [importing \`baar\` from \`entry.js\`]"`)
3333
})
3434

35+
it('should handle functional patterns', async () => {
36+
const result = await process(code('bar'), { patterns: [[id => id === 'bar']] }) as RollupError
37+
expect(result.message).toMatchInlineSnapshot(`"[plugin impound] Invalid import [importing \`bar\` from \`entry.js\`]"`)
38+
39+
const result2 = await process(code('bar'), { patterns: [[id => id === 'bar' ? 'boo!' : false]] }) as RollupError
40+
expect(result2.message).toMatchInlineSnapshot(`"[plugin impound] boo! [importing \`bar\` from \`entry.js\`]"`)
41+
})
42+
3543
it('should handle error: false', async () => {
3644
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
3745
const result = await process(code('bar'), { patterns: [['bar']], error: false }) as RollupError

0 commit comments

Comments
 (0)