【问题标题】:Using ES6 classes with ES5 code [duplicate]使用带有 ES5 代码的 ES6 类 [重复]
【发布时间】:2017-03-22 05:30:08
【问题描述】:

我终于要搭乘 ES6 火车了。我使用 ES6 和 Babel 编写了一个小型 Node.js 应用程序进行编译。我正在使用 Mocha 编写测试,据我所知,您现在还不应该使用 ES6。

我正在尝试测试我制作的对象类的一些功能。因此,在 Mocha 中,我正在执行以下操作:

var assert = require('assert');
var Icon = require('../lib/icon');

describe('Icons', function() {
  describe('#save()', function() {
    it('should return a success message & save the icon', function() {
        var icon = new Icon('https://cdn4.iconfinder.com/data/icons/social-media-2070/140/_whatsapp-128.png', 'icon-test');
        var result = Icon.save();

        if(result !== '_whatsapp-128.png saved successfully.') return false;

        return fs.existsSync('icon-test/_whatsapp-128.png');
    });
  });
});

这显然是行不通的:

var icon = new Icon('https://cdn4.iconfinder.com/data/icons/social-media-2070/140/_whatsapp-128.png', 'icon-test');

我不太确定如何使用 ES5 实例化 ES6 对象,然后测试函数。任何帮助将不胜感激。

** 编辑 - 添加图标文件 **

import fs from 'fs';
import https from 'https';
import path from 'path';

class Icon {
    constructor(source, destination) {
        this.source = source;
        this.destination = path.resolve(destination);
    }

    save() {
        console.log(this.source);
        // Fetching the icon.
        let request = https.get(this.source, (response) => {

            // Splitting the file information.
            let fileInfo = path.parse(this.source);

            // Creating the directory, if it does not already exist.
            if(!fs.existsSync(this.destination)) {
                fs.mkdirSync(this.destination);
                console.log('Destination directory created.\n');
            }

            // Piping the icon data & saving onto disk.
            let iconFile = fs.createWriteStream(this.destination + '/' + fileInfo.base);
            response.pipe(iconFile);
            return `${fileInfo.base} saved successfully.`;
        });
    }
}

export default Icon;

【问题讨论】:

  • "这显然行不通" 为什么不呢? ES5 中存在对象,只是 class 语法是新的。
  • 反对 'ES6' 和 'ES5' 是没有意义的。是JS。请提供有关问题所在的详细信息。错误消息和../lib/icon 的列表会有所帮助。从 ES6 模块中以var Icon = require('../lib/icon') 的形式成功导入一个类是不太可能的。
  • 错误信息:Type Error: Icon is not a constructor
  • 那么它可以被信任——它不是。它可能是 ES6 模块。这是一个对象而不是构造函数。可以记录和检查的是您,而不是其他任何人。该问题没有包含足够的细节并鼓励猜测。

标签: javascript node.js ecmascript-6 mocha.js


【解决方案1】:

../lib/icon 是具有默认导出的 ES6 模块。

require('../lib/icon') 返回 ES6 模块对象。要要求默认导出,它应该是

var Icon = require('../lib/icon').default;

【讨论】:

    【解决方案2】:

    使用 es6-shim 或 es5-shim(参见此处 https://github.com/paulmillr/es6-shim)使其在 ECMA 脚本 5 中工作。如果不能使用它,还包括其他库以获得旧支持,您可以在此处找到 @ 987654322@ 用于 polyfills 和所有其他东西。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多