@@ -2,6 +2,7 @@ const t = require('babel-types');
22const Path = require ( 'path' ) ;
33const fs = require ( 'fs' ) ;
44const template = require ( 'babel-template' ) ;
5+ const logger = require ( '../Logger' ) ;
56
67const bufferTemplate = template ( 'Buffer(CONTENT, ENC)' ) ;
78
@@ -31,12 +32,32 @@ module.exports = {
3132 __dirname : Path . dirname ( asset . name ) ,
3233 __filename : asset . basename
3334 } ;
34- let [ filename , ...args ] = path
35- . get ( 'arguments' )
36- . map ( arg => evaluate ( arg , vars ) ) ;
37- filename = Path . resolve ( filename ) ;
35+ let filename , args , res ;
36+
37+ try {
38+ [ filename , ...args ] = path
39+ . get ( 'arguments' )
40+ . map ( arg => evaluate ( arg , vars ) ) ;
41+
42+ filename = Path . resolve ( filename ) ;
43+ res = fs . readFileSync ( filename , ...args ) ;
44+ } catch ( err ) {
45+ if ( err instanceof NodeNotEvaluatedError ) {
46+ // Warn using a code frame
47+ err . fileName = asset . name ;
48+ asset . generateErrorMessage ( err ) ;
49+ logger . warn ( err ) ;
50+ return ;
51+ }
52+
53+ // Add location info so we log a code frame with the error
54+ err . loc =
55+ path . node . arguments . length > 0
56+ ? path . node . arguments [ 0 ] . loc . start
57+ : path . node . loc . start ;
58+ throw err ;
59+ }
3860
39- let res = fs . readFileSync ( filename , ...args ) ;
4061 let replacementNode ;
4162 if ( Buffer . isBuffer ( res ) ) {
4263 replacementNode = bufferTemplate ( {
@@ -153,6 +174,12 @@ function getBindingPath(path, name) {
153174 return binding && binding . path ;
154175}
155176
177+ function NodeNotEvaluatedError ( node ) {
178+ this . message = 'Cannot statically evaluate fs argument' ;
179+ this . node = node ;
180+ this . loc = node . loc . start ;
181+ }
182+
156183function evaluate ( path , vars ) {
157184 // Inline variables
158185 path . traverse ( {
@@ -165,8 +192,9 @@ function evaluate(path, vars) {
165192 } ) ;
166193
167194 let res = path . evaluate ( ) ;
195+
168196 if ( ! res . confident ) {
169- throw new Error ( 'Could not statically evaluate fs call' ) ;
197+ throw new NodeNotEvaluatedError ( path . node ) ;
170198 }
171199
172200 return res . value ;
0 commit comments