diff --git a/src/generate-import.ts b/src/generate-import.ts index 09773fb..a56dca9 100644 --- a/src/generate-import.ts +++ b/src/generate-import.ts @@ -1,3 +1,4 @@ +import type { ImportType } from 'src' import type { Analyzed } from './analyze' export interface ImportRecord { @@ -6,7 +7,7 @@ export interface ImportRecord { importedName?: string } -export function generateImport(analyzed: Analyzed) { +export function generateImport(analyzed: Analyzed, id: string, rules?: ImportType | ((id: string) => ImportType)) { const imports: ImportRecord[] = [] let count = 0 @@ -35,8 +36,29 @@ export function generateImport(analyzed: Analyzed) { } // This is probably less accurate but is much cheaper than a full AST parse. + let importType: ImportType = 'defaultFirst' + if (rules) { + if (typeof rules === 'string') { + importType = rules + } + if (typeof rules === 'function') { + importType = rules(id) || 'defaultFirst' + } + } impt.importExpression = `import * as ${importName} from '${requireId}'` - impt.importedName = `${importName}.default || ${importName}` // Loose + switch (importType) { + case 'defaultFirst': + impt.importedName = `${importName}.default || ${importName}` + break + case 'namedFirst': + impt.importedName = `Object.keys(${importName}).join('') !== 'default' ? ${importName} : ${importName}.default` + break + case 'merge': + impt.importedName = `${importName}.default ? Object.assign(${importName}.default, ${importName}) : ${importName}`; + break + default: + throw new Error(`Unknown import type: ${importType} for ${id}`) + } imports.push(impt) } diff --git a/src/index.ts b/src/index.ts index beb583b..657e449 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,6 +20,8 @@ import { DynaimcRequire } from './dynamic-require' export const TAG = '[vite-plugin-commonjs]' +export type ImportType = 'defaultFirst' | 'namedFirst' | 'merge' + export interface Options { filter?: (id: string) => boolean | undefined dynamic?: { @@ -42,6 +44,9 @@ export interface Options { */ onFiles?: (files: string[], id: string) => typeof files | undefined } + advanced?: { + importRules?: ImportType | ((id: string) => ImportType) + } } export default function commonjs(options: Options = {}): Plugin { @@ -140,7 +145,7 @@ async function transformCommonjs({ } const analyzed = analyzer(ast, code, id) - const imports = generateImport(analyzed) + const imports = generateImport(analyzed, id, options.advanced?.importRules) const exportRuntime = id.includes('node_modules/.vite') // Bypass Pre-build ? null