diff --git a/README.md b/README.md index e777696..24553af 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,21 @@ export interface CommonjsOptions { onFiles?: (files: string[], id: string) => typeof files | undefined } advanced?: { - /** - * Custom import module interop behavior. - * - * If you want to fully customize the interop behavior, - * you can pass a function and return the interop code snippet. - */ - importRules?: ImportInteropType | ((id: string) => ImportInteropType | string) + /** + * Custom import module interop behavior. + * + * If you want to fully customize the interop behavior, + * you can pass a function and return the interop code snippet. + */ + importRules?: ImportInteropType | ((id: string) => ImportInteropType | string) + + /** + * Custom import ID handler. + * + * If you want to fully customize the generated import value, + * you can pass a function and return the proper name. + */ + namingRules?: (id: string, node: AcornNode) => string } } ``` diff --git a/src/generate-import.ts b/src/generate-import.ts index 59894a6..6126e53 100644 --- a/src/generate-import.ts +++ b/src/generate-import.ts @@ -8,7 +8,7 @@ export interface ImportRecord { } export function generateImport(analyzed: Analyzed, id: string, options: CommonjsOptions) { - const { importRules } = options.advanced ?? {} + const { namingRules, importRules } = options.advanced ?? {} const imports: ImportRecord[] = [] let count = 0 @@ -36,6 +36,10 @@ export function generateImport(analyzed: Analyzed, id: string, options: Commonjs ${'^'.repeat(codeSnippets.length)}`) } + if (typeof namingRules === 'function') { + requireId = namingRules(requireId, node) + } + // This is probably less accurate, but is much cheaper than a full AST parse. let importInterop: ImportInteropType | string = 'defaultFirst' if (typeof importRules === 'string') { diff --git a/src/index.ts b/src/index.ts index c5b2e7c..7b0efe0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -51,7 +51,15 @@ export interface CommonjsOptions { * If you want to fully customize the interop behavior, * you can pass a function and return the interop code snippet. */ - importRules?: ImportInteropType | ((id: string) => ImportInteropType | string) + importRules?: ImportInteropType | ((id: string) => ImportInteropType | string), + + /** + * Custom import ID handler. + * + * If you want to fully customize the generated import value, + * you can pass a function and return the proper name. + */ + namingRules?: (id: string, node: AcornNode) => string } }