-
-
Notifications
You must be signed in to change notification settings - Fork 261
feat: add cjsInterop support without splitting flag #1056
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tmkx
wants to merge
1
commit into
egoist:main
Choose a base branch
from
tmkx:fix/cjs-interop
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,114 @@ | ||
import type { | ||
ExportDefaultExpression, | ||
ModuleDeclaration, | ||
ParseOptions, | ||
} from '@swc/core' | ||
import type { Visitor } from '@swc/core/Visitor' | ||
import fs from 'fs/promises' | ||
import path from 'path' | ||
import { PrettyError } from '../errors' | ||
import { Plugin } from '../plugin' | ||
import { localRequire } from '../utils' | ||
|
||
export const cjsInterop = (): Plugin => { | ||
return { | ||
name: 'cjs-interop', | ||
|
||
async renderChunk(code, info) { | ||
const { entryPoint } = info | ||
if ( | ||
!this.options.cjsInterop || | ||
this.format !== 'cjs' || | ||
info.type !== 'chunk' || | ||
!/\.(js|cjs)$/.test(info.path) || | ||
!info.entryPoint || | ||
info.exports?.length !== 1 || | ||
info.exports[0] !== 'default' | ||
!entryPoint | ||
) { | ||
return | ||
} | ||
|
||
if (this.splitting) { | ||
// there is exports metadata when cjs+splitting is set | ||
if (info.exports?.length !== 1 || info.exports[0] !== 'default') return | ||
} else { | ||
const swc: typeof import('@swc/core') = localRequire('@swc/core') | ||
const { Visitor }: typeof import('@swc/core/Visitor') = | ||
localRequire('@swc/core/Visitor') | ||
if (!swc || !Visitor) { | ||
throw new PrettyError( | ||
`@swc/core is required for cjsInterop when splitting is not enabled. Please install it with \`npm install @swc/core -D\`` | ||
) | ||
} | ||
|
||
try { | ||
const entrySource = await fs.readFile(entryPoint, { | ||
encoding: 'utf8', | ||
}) | ||
const parseOptions = getParseOptions(entryPoint) | ||
if (!parseOptions) return | ||
const ast = await swc.parse(entrySource, parseOptions) | ||
const visitor = createExportVisitor(Visitor) | ||
visitor.visitProgram(ast) | ||
|
||
if ( | ||
!visitor.hasExportDefaultExpression || | ||
visitor.hasNonDefaultExportDeclaration | ||
) | ||
return | ||
} catch { | ||
return | ||
} | ||
} | ||
|
||
return { | ||
code: code + '\nmodule.exports = exports.default;\n', | ||
code: code + '\nmodule.exports=module.exports.default;\n', | ||
sxzz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
map: info.map, | ||
} | ||
}, | ||
} | ||
} | ||
|
||
function getParseOptions(filename: string): ParseOptions | null { | ||
if (/\.([cm]?js|jsx)$/.test(filename)) | ||
return { | ||
syntax: 'ecmascript', | ||
decorators: true, | ||
jsx: filename.endsWith('.jsx'), | ||
} | ||
if (/\.([cm]?ts|tsx)$/.test(filename)) | ||
return { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Merge the object with previous one. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. how to merge the objects? it's a union type: type ParserConfig = TsParserConfig | EsParserConfig |
||
syntax: 'typescript', | ||
decorators: true, | ||
tsx: filename.endsWith('.tsx'), | ||
} | ||
return null | ||
} | ||
|
||
function createExportVisitor(VisitorCtor: typeof Visitor) { | ||
class ExportVisitor extends VisitorCtor { | ||
hasNonDefaultExportDeclaration = false | ||
hasExportDefaultExpression = false | ||
constructor() { | ||
super() | ||
type ExtractDeclName<T> = T extends `visit${infer N}` ? N : never | ||
const nonDefaultExportDecls: ExtractDeclName<keyof Visitor>[] = [ | ||
'ExportDeclaration', // export const a = {} | ||
'ExportNamedDeclaration', // export {}, export * as a from './a' | ||
'ExportAllDeclaration', // export * from './a' | ||
] | ||
|
||
nonDefaultExportDecls.forEach((decl) => { | ||
this[`visit${decl}`] = (n: any) => { | ||
this.hasNonDefaultExportDeclaration = true | ||
return n | ||
} | ||
}) | ||
} | ||
visitExportDefaultExpression( | ||
n: ExportDefaultExpression | ||
): ModuleDeclaration { | ||
this.hasExportDefaultExpression = true | ||
return n | ||
} | ||
} | ||
return new ExportVisitor() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.