ES6 module import is not defined during debugger

拥有回忆 提交于 2019-12-09 07:48:45

问题


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' }
        ]
    }
};

回答1:


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.



来源:https://stackoverflow.com/questions/30161123/es6-module-import-is-not-defined-during-debugger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!