@@ -9,6 +9,7 @@ const {getName, getIdentifier} = require('./utils');
9
9
10
10
const EXPORTS_RE = / ^ \$ ( [ ^ $ ] + ) \$ e x p o r t s $ / ;
11
11
12
+ const ESMODULE_TEMPLATE = template ( `$parcel$defineInteropFlag(EXPORTS);` ) ;
12
13
const DEFAULT_INTEROP_TEMPLATE = template (
13
14
'var NAME = $parcel$interopDefault(MODULE)'
14
15
) ;
@@ -142,10 +143,11 @@ module.exports = (packager, ast) => {
142
143
) ;
143
144
}
144
145
146
+ let asset = assets . get ( id . value ) ;
145
147
let mod = packager . resolveModule ( id . value , source . value ) ;
146
148
147
149
if ( ! mod ) {
148
- if ( assets . get ( id . value ) . dependencies . get ( source . value ) . optional ) {
150
+ if ( asset . dependencies . get ( source . value ) . optional ) {
149
151
path . replaceWith (
150
152
THROW_TEMPLATE ( { MODULE : t . stringLiteral ( source . value ) } )
151
153
) ;
@@ -161,6 +163,29 @@ module.exports = (packager, ast) => {
161
163
if ( ! isUnusedValue ( path ) ) {
162
164
let name = getName ( mod , 'exports' ) ;
163
165
node = t . identifier ( replacements . get ( name ) || name ) ;
166
+
167
+ // Insert __esModule interop flag if the required module is an ES6 module with a default export.
168
+ // This ensures that code generated by Babel and other tools works properly.
169
+ if (
170
+ asset . cacheData . isCommonJS &&
171
+ mod . cacheData . isES6Module &&
172
+ mod . cacheData . exports . default
173
+ ) {
174
+ let binding = path . scope . getBinding ( name ) ;
175
+ if ( binding && ! binding . path . getData ( 'hasESModuleFlag' ) ) {
176
+ if ( binding . path . node . init ) {
177
+ binding . path
178
+ . getStatementParent ( )
179
+ . insertAfter ( ESMODULE_TEMPLATE ( { EXPORTS : name } ) ) ;
180
+ }
181
+
182
+ for ( let path of binding . constantViolations ) {
183
+ path . insertAfter ( ESMODULE_TEMPLATE ( { EXPORTS : name } ) ) ;
184
+ }
185
+
186
+ binding . path . setData ( 'hasESModuleFlag' , true ) ;
187
+ }
188
+ }
164
189
}
165
190
166
191
// We need to wrap the module in a function when a require
0 commit comments