2020-07-11 04:30:58 +08:00
|
|
|
import { parse, ParserPlugin } from '@babel/parser'
|
|
|
|
import MagicString from 'magic-string'
|
|
|
|
|
2020-07-23 09:00:41 +08:00
|
|
|
const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/
|
|
|
|
const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/
|
2020-07-11 04:30:58 +08:00
|
|
|
|
|
|
|
/**
|
2020-08-15 05:05:12 +08:00
|
|
|
* Utility for rewriting `export default` in a script block into a variable
|
2020-07-11 04:30:58 +08:00
|
|
|
* declaration so that we can inject things into it
|
|
|
|
*/
|
|
|
|
export function rewriteDefault(
|
|
|
|
input: string,
|
|
|
|
as: string,
|
|
|
|
parserPlugins?: ParserPlugin[]
|
|
|
|
): string {
|
2020-07-23 09:00:41 +08:00
|
|
|
if (!hasDefaultExport(input)) {
|
2020-07-11 04:30:58 +08:00
|
|
|
return input + `\nconst ${as} = {}`
|
|
|
|
}
|
|
|
|
|
|
|
|
const replaced = input.replace(defaultExportRE, `$1const ${as} =`)
|
2020-07-23 09:00:41 +08:00
|
|
|
if (!hasDefaultExport(replaced)) {
|
2020-07-11 04:30:58 +08:00
|
|
|
return replaced
|
|
|
|
}
|
|
|
|
|
|
|
|
// if the script somehow still contains `default export`, it probably has
|
|
|
|
// multi-line comments or template strings. fallback to a full parse.
|
|
|
|
const s = new MagicString(input)
|
|
|
|
const ast = parse(input, {
|
2020-07-23 09:00:41 +08:00
|
|
|
sourceType: 'module',
|
2020-07-11 04:30:58 +08:00
|
|
|
plugins: parserPlugins
|
|
|
|
}).program.body
|
|
|
|
ast.forEach(node => {
|
|
|
|
if (node.type === 'ExportDefaultDeclaration') {
|
|
|
|
s.overwrite(node.start!, node.declaration.start!, `const ${as} = `)
|
|
|
|
}
|
2020-07-23 09:00:41 +08:00
|
|
|
if (node.type === 'ExportNamedDeclaration') {
|
|
|
|
node.specifiers.forEach(specifier => {
|
|
|
|
if (
|
|
|
|
specifier.type === 'ExportSpecifier' &&
|
|
|
|
specifier.exported.name === 'default'
|
|
|
|
) {
|
|
|
|
const end = specifier.end!
|
|
|
|
s.overwrite(
|
|
|
|
specifier.start!,
|
|
|
|
input.charAt(end) === ',' ? end + 1 : end,
|
|
|
|
``
|
|
|
|
)
|
|
|
|
s.append(`\nconst ${as} = ${specifier.local.name}`)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2020-07-11 04:30:58 +08:00
|
|
|
})
|
|
|
|
return s.toString()
|
|
|
|
}
|
2020-07-23 09:00:41 +08:00
|
|
|
|
|
|
|
export function hasDefaultExport(input: string): boolean {
|
|
|
|
return defaultExportRE.test(input) || namedDefaultExportRE.test(input)
|
|
|
|
}
|