Skip to content

Commit

Permalink
feat: support advanced import rules option
Browse files Browse the repository at this point in the history
  • Loading branch information
Jinjiang committed Aug 25, 2023
1 parent a0207e0 commit c1e1ceb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
26 changes: 24 additions & 2 deletions src/generate-import.ts
@@ -1,3 +1,4 @@
import type { ImportType } from 'src'
import type { Analyzed } from './analyze'

export interface ImportRecord {
Expand All @@ -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

Expand Down Expand Up @@ -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)
}
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Expand Up @@ -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?: {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit c1e1ceb

Please sign in to comment.