ES6 module import is not defined during debugger
Asked Answered
A

3

25

While playing around with Babel and Webpack I stumbled into some really weird behavior today.

I threw a debugger in my main.js to see if I was importing correctly, but Chrome's console kept yelling that the module I was trying to import was not defined. I try console logging the same module instead, and I see it printed to my console.

What gives? I've pasted the relevant code snippets below:

main.js

import Thing from './Thing.js';

debugger // if you type Thing into the console, it is not defined

console.log(new Thing()); // if you let the script finish running, this works

thing.js

class Thing {
}

export default Thing;

webpack.config.js

var path = require('path');
module.exports = {
    entry: './js/main.js',
    output: {
        path: __dirname,
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            { test: path.join(__dirname, 'js'), loader: 'babel-loader' }
        ]
    }
};
Arcade answered 11/5, 2015 at 6:45 Comment(0)
E
29

tl;dr: Babel does not necessarily preserve variables names.


If we look at the code generated from

import Thing from './Thing.js';

debugger;

console.log(new Thing());

namely:

'use strict';

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _ThingJs = require('./Thing.js');

var _ThingJs2 = _interopRequireDefault(_ThingJs);

debugger;

console.log(new _ThingJs2['default']());

We see that Things is not defined indeed. So Chrome is correct.

Etherege answered 11/5, 2015 at 13:42 Comment(4)
Awesome, thanks for the quick reply! I wonder if turning on source maps would change this behavior..?Arcade
Making debugger useless is a pretty big con IMO, I find it hard to believe Babel would allow thatArcade
Why useless debugger is a pretty con?Bard
To be clear, you can just use the awkward webpack/babel name. In my case, this was more like _ThingJs2__default(), but YMMV.Biscuit
M
4

In some debugging scenarios, it may be sufficient to assign the imported variable to a new variable in local scope. For example:

import Thing from './Thing.js';
const TestThing = Thing;

debugger; // although Thing will not be defined, TestThing will be defined

console.log(new TestThing());

This doesn't fix the core issue at hand, but it can be a workaround for debugging in certain situations.

Marchellemarcher answered 16/4, 2020 at 9:11 Comment(0)
A
0

You can try my webpack plugin which defines debug vars for imports so that they are available in the debugger.

https://github.com/trias/debug-import-vars-webpack-plugin

Adulterant answered 5/2, 2022 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.