7
7
const REQUIRE_ANYTHING_BASE = 'require\\s*\\(([^)]+)\\)' ;
8
8
const REQUIRE_ANYTHING_REGEX = new RegExp ( REQUIRE_ANYTHING_BASE , 'g' ) ;
9
9
10
+ const IMPORT_ANYTHING_BASE = 'import .+ from (.+)' ;
11
+ const IMPORT_ANYTHING_REGEX = new RegExp ( IMPORT_ANYTHING_BASE , 'g' ) ;
12
+
10
13
const SIMPLE_STRING_REGEX = / ^ " ( [ ^ " ] + ) " $ | ^ ' ( [ ^ ' ] + ) ' $ / ;
11
14
15
+ function getRequiresWithRegex ( code , regex , requires ) {
16
+ code . replace ( regex , function ( requireExprMatch , requiredExpr ) {
17
+ const requireStrMatch = SIMPLE_STRING_REGEX . exec ( requiredExpr . trim ( ) ) ;
18
+ if ( ! requireStrMatch ) {
19
+ throw new Error ( `Requires using expressions are not supported in examples. (Used: ${ requireExprMatch } )` ) ;
20
+ }
21
+ const requiredString = requireStrMatch [ 1 ] ? requireStrMatch [ 1 ] : requireStrMatch [ 2 ] ;
22
+ requires [ requiredString ] = true ;
23
+ } ) ;
24
+ }
25
+
12
26
/**
13
27
* Returns a list of all strings used in require(...) calls in the given source code.
14
28
* If there is any other expression inside the require call, it throws an error.
@@ -18,14 +32,9 @@ const SIMPLE_STRING_REGEX = /^"([^"]+)"$|^'([^']+)'$/;
18
32
*/
19
33
module . exports = function getRequires ( code ) {
20
34
const requires = { } ;
21
- code . replace ( REQUIRE_ANYTHING_REGEX , function ( requireExprMatch , requiredExpr ) {
22
- const requireStrMatch = SIMPLE_STRING_REGEX . exec ( requiredExpr . trim ( ) ) ;
23
- if ( ! requireStrMatch ) {
24
- throw new Error ( `Requires using expressions are not supported in examples. (Used: ${ requireExprMatch } )` ) ;
25
- }
26
- const requiredString = requireStrMatch [ 1 ] ? requireStrMatch [ 1 ] : requireStrMatch [ 2 ] ;
27
- requires [ requiredString ] = true ;
28
- } ) ;
35
+ getRequiresWithRegex ( code , REQUIRE_ANYTHING_REGEX , requires ) ;
36
+ getRequiresWithRegex ( code , IMPORT_ANYTHING_REGEX , requires ) ;
37
+
29
38
return Object . keys ( requires ) ;
30
39
} ;
31
40
0 commit comments