1
1
import { parse , ParserPlugin } from '@babel/parser'
2
2
import MagicString from 'magic-string'
3
3
4
- const defaultExportRE = / ( (?: ^ | \n | ; ) \s * ) e x p o r t d e f a u l t /
4
+ const defaultExportRE = / ( (?: ^ | \n | ; ) \s * ) e x p o r t ( \s * ) d e f a u l t /
5
+ const namedDefaultExportRE = / ( (?: ^ | \n | ; ) \s * ) e x p o r t ( .+ ) a s ( \s * ) d e f a u l t /
5
6
6
7
/**
7
8
* Utility for rewriting `export default` in a script block into a varaible
@@ -12,25 +13,46 @@ export function rewriteDefault(
12
13
as : string ,
13
14
parserPlugins ?: ParserPlugin [ ]
14
15
) : string {
15
- if ( ! defaultExportRE . test ( input ) ) {
16
+ if ( ! hasDefaultExport ( input ) ) {
16
17
return input + `\nconst ${ as } = {}`
17
18
}
18
19
19
20
const replaced = input . replace ( defaultExportRE , `$1const ${ as } =` )
20
- if ( ! defaultExportRE . test ( replaced ) ) {
21
+ if ( ! hasDefaultExport ( replaced ) ) {
21
22
return replaced
22
23
}
23
24
24
25
// if the script somehow still contains `default export`, it probably has
25
26
// multi-line comments or template strings. fallback to a full parse.
26
27
const s = new MagicString ( input )
27
28
const ast = parse ( input , {
29
+ sourceType : 'module' ,
28
30
plugins : parserPlugins
29
31
} ) . program . body
30
32
ast . forEach ( node => {
31
33
if ( node . type === 'ExportDefaultDeclaration' ) {
32
34
s . overwrite ( node . start ! , node . declaration . start ! , `const ${ as } = ` )
33
35
}
36
+ if ( node . type === 'ExportNamedDeclaration' ) {
37
+ node . specifiers . forEach ( specifier => {
38
+ if (
39
+ specifier . type === 'ExportSpecifier' &&
40
+ specifier . exported . name === 'default'
41
+ ) {
42
+ const end = specifier . end !
43
+ s . overwrite (
44
+ specifier . start ! ,
45
+ input . charAt ( end ) === ',' ? end + 1 : end ,
46
+ ``
47
+ )
48
+ s . append ( `\nconst ${ as } = ${ specifier . local . name } ` )
49
+ }
50
+ } )
51
+ }
34
52
} )
35
53
return s . toString ( )
36
54
}
55
+
56
+ export function hasDefaultExport ( input : string ) : boolean {
57
+ return defaultExportRE . test ( input ) || namedDefaultExportRE . test ( input )
58
+ }
0 commit comments