@@ -8,20 +8,26 @@ import requireIt from './requireIt';
8
8
* @param name the name of the resulting variable
9
9
* @returns AST
10
10
*/
11
- export default ( requireRequest : string , name : string ) => [
12
- // const name$0 = require(path);
13
- b . variableDeclaration ( 'const' , [
14
- b . variableDeclarator ( b . identifier ( `${ name } $0` ) , requireIt ( requireRequest ) . toAST ( ) as any ) ,
15
- ] ) ,
16
- // const name = name$0.default || name$0[name] || name$0;
17
- b . variableDeclaration ( 'const' , [
18
- b . variableDeclarator (
19
- b . identifier ( name ) ,
20
- b . logicalExpression (
21
- '||' ,
22
- b . identifier ( `${ name } $0.default` ) ,
23
- b . logicalExpression ( '||' , b . identifier ( `${ name } $0['${ name } ']` ) , b . identifier ( `${ name } $0` ) )
24
- )
25
- ) ,
26
- ] ) ,
27
- ] ;
11
+ export default ( requireRequest : string , name : string ) => {
12
+ // The name could possibly contain invalid characters for a JS variable name
13
+ // such as "." or "-".
14
+ const safeName = name ? name . replace ( / \W / , '' ) : name ;
15
+
16
+ return [
17
+ // const safeName$0 = require(path);
18
+ b . variableDeclaration ( 'const' , [
19
+ b . variableDeclarator ( b . identifier ( `${ safeName } $0` ) , requireIt ( requireRequest ) . toAST ( ) as any ) ,
20
+ ] ) ,
21
+ // const safeName = safeName$0.default || safeName$0[safeName] || safeName$0;
22
+ b . variableDeclaration ( 'const' , [
23
+ b . variableDeclarator (
24
+ b . identifier ( safeName ) ,
25
+ b . logicalExpression (
26
+ '||' ,
27
+ b . identifier ( `${ safeName } $0.default` ) ,
28
+ b . logicalExpression ( '||' , b . identifier ( `${ safeName } $0['${ safeName } ']` ) , b . identifier ( `${ safeName } $0` ) )
29
+ )
30
+ ) ,
31
+ ] ) ,
32
+ ]
33
+ } ;
0 commit comments