使用 BabelJs 转译时如何忽略一段代码?

How to ignore a block of code when transpiling with BabelJs?

我正在尝试使用 Babeljs 在 ES2015 中引用 this。我遇到的这个问题是 Babeljs 一直将 this 移出范围进入外部范围。这破坏了代码。我希望 Babeljs 有评论,或者我可以使用某种块符号来让它忽略代码,这样它就不会被转译。

如果那里有 Mongoose 大师,也许还有另一种方法可以访问 属性 和相关功能 (this.isNew || this.isModified('email'))。

这是 ES2015 代码。

setDuplicateEmailValidation(){
    this.schema.path('email').validate((email, fn) => {
        let User = mongoose.model('User');

        // Check only when it is a new user or when email field is modified
        if (this.isNew || this.isModified('email')) {
            User.find({ email: email }).exec((err, users) => {
                fn(!err && users.length === 0);
            });
        } else fn(true);
    }, 'Email already exists');
}

在 if 语句 if (this.isNew || this.isModified('email')) 中,预编译代码引用了 thisvalidate() 的范围很重要,因为在这个范围内我可以访问 Mongoosejs's Document API。一旦代码移出 validate() 范围,我就无法再访问文档 API.

转译后的代码。

function setDuplicateEmailValidation() {
            var _this = this;
        this.schema.path('email').validate(function (email, fn) {
            var User = _mongoose2['default'].model('User');

            // Check only when it is a new user or when email field is modified
            if (_this.isNew || _this.isModified('email')) {
                User.find({ email: email }).exec(function (err, users) {
                    fn(!err && users.length === 0);
                });
            } else fn(true);
        }, 'Email already exists');
    }
}

在此代码中,您会注意到 if 语句引用了验证函数范围之外的变量 (if (_this.isNew || _this.isModified('email')))。由于这个(没有双关语意)移动,我无法访问 Mongoosejs 的文档 API。

如有任何建议,我们将不胜感激。

不要使用arrow function,只使用function关键字:

this.schema.path('email').validate(function (email, fn) {

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.

强调我的。这意味着箭头函数内部的 this 将在箭头函数外部的相同词法上下文中 this 。这是故意的,不同于 function 语法。