首页 > 解决方案 > 如何避免 babel 的 'Uncaught ReferenceError: stringClasses is not defined'?

问题描述

我有一个要缩小的 javascript 代码。我正在使用 gulp 任务来做到这一点:

...
gulp.task('app.js', () => {
    return gulp.src('src/assets/js/*.js')
        .pipe(babel({presets: ['env']}))
        .pipe(uglify())
        .pipe(gulp.dest('src/public/js'))
})
...

但我注意到,当我尝试使用这个缩小的 javascript 访问加载 html 的页面时,我遇到了一个 javascript 错误:

Uncaught ReferenceError: stringClasses is not defined
    at newElement (jv.js:1)
    at new Screen (jv.js:1)
    at HashGame (jv.js:1)
    at jv.js:1

所以我认为这是uglify()函数的问题并删除了 uglify 步骤,但问题仍然存在(所以问题是 babel):

Uncaught ReferenceError: stringClasses is not defined
    at newElement (jv.js:12)
    at new Screen (jv.js:137)
    at HashGame (jv.js:153)
    at jv.js:162

原来的 newElement 函数是:

function Item(id){
    this.elem = newElement('div', 'item', 'pencilBorder')
    this.elem.id = id
    this.play = (checker) => {
        if (!this.elem.attributes.filled){
            this.elem.innerHTML = 'X'
            this.elem.attributes.value = 'X'
            this.elem.setAttribute("filled", true)
            if (!checker.check()){
                robotPlay()
                checker.check()
            }
        }
    }
    this.elem.onclick = (e) => {
        this.play(new Checker())
    }
}

babel 将其更改为:

function newElement(tagName) {
    var elem = document.createElement(tagName);

    for (var _len = arguments.length, classNames = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        classNames[_key - 1] = arguments[_key];
    }

    stringClasses = classNames.reduce(function (ac, current) {
        return ac + " " + current;
    });
    elem.className = stringClasses;
    return elem;
}

我搜索了 babel 选项并尝试了新的预设,但没有任何效果。有谁知道如何解决它?

标签: javascriptgulpbabeljs

解决方案


所以我发现了问题:这是我的功能newElement

我在它之前声明了没有 var/let 或 const 的变量 stringClasses,如果我不使用 babel,它就可以工作。但是当 babel 为 es2015 更改它时,这会引发一个问题。


推荐阅读