Ошибка типа: _food2.default не является конструктором - PullRequest
0 голосов
/ 24 июня 2018

У меня проблема с моим Food классом, который я создал для трекера еды, который я хочу создать.Он отлично работает в одном файле, но не в другом.

Это класс:

import uuidv4 from 'uuid/v4'
import moment from 'moment'
import { throwIfNotAString, throwIfNotANumber } from './functions'

class Food {
    constructor(id, ean, createdAt, updatedAt, brand, name, calories, protein, carbohydrate, fat, saturatedFat, multipleUnsaturatedFat, basicUnsaturatedFat, transFat, cholesterol, natrium, potassium, fibers, sugar, portion, portionUnit, portionAmount, names, brands) {
        const timestamp = moment().valueOf()
        this._id = id || uuidv4()
        this._ean = ean || null
        this.createdAt = createdAt || timestamp
        this.updatedAt = updatedAt || timestamp
        this._brand = brand.trim()
        this._name = name.trim()
        this._calories = calories
        this._protein = protein
        this._carbohydrate = carbohydrate
        this._fat = fat
        this._saturatedFat = saturatedFat || null
        this._multipleUnsaturatedFat = multipleUnsaturatedFat || null
        this._basicUnsaturatedFat = basicUnsaturatedFat || null
        this._transFat = transFat || null
        this._cholesterol = cholesterol || null
        this._natrium = natrium || null
        this._potassium = potassium || null                             // Kalium
        this._fibers = fibers || null                                   // Ballaststoffe
        this._sugar = sugar || null
        this._portion = portion || null                                 // e.g. 100
        this._portionUnit = portionUnit || null                         // e.g. 'g'
        this._portionAmount = portionAmount || 1                                         
        this._names = names || []
        this._names.push(this._name)
        this._brands = brands || []
        this._brands.push(this._brand)
    }

    get id() {
        return this._id
    }

    get ean() {
        return this._ean
    }

    get brand() {
        return this._brand
    }

    get name() {
        return this._name
    }

    get calories() {
        return this._calories
    }

    get macronutrients() {
        return {
            protein: this._protein,
            carbohydrate: this._carbohydrate,
            fat: this._fat
        }
    }

    set ean(value) {
        if (typeof value === 'number') {
            this._ean = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('EAN')
        }
    }

    set brand(value) {
        if (typeof value === 'string') {
            this._brand = value.trim()
            this._brands.push(this._brand)
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'string') {
            throwIfNotAString('Brand')
        }
    }

    set name(value) {
        if (typeof value === 'string') {
            this._name = value.trim()
            this._names.push(this._name)
            this.updatedAt = moment().valueOf()
        } else if (typeof valule !== 'string') {
            throwIfNotAString('Name')
        }
    }

    set calories(value) {
        if (typeof value === 'number') {
            this._calories = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('Calories')
        }
    }

    set protein(value) {
        if (typeof value === 'number') {
            this._protein = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('Protein')
        }
    }

    set carbohydrate(value) {
        if (typeof value === 'number') {
            this._carbohydrate = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('Carbohydrate')
        }
    }

    set fat(value) {
        if (typeof value === 'number') {
            this._fat = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('Fat')
        }
    }

    set portion(value) {
        if (typeof value === 'number') {
            this._portion = value
            this.updatedAt = moment().valueOf()
        } else if (typeof value !== 'number') {
            throwIfNotANumber('Portion')
        }
    }
}

export { Food as default }

Я экспортирую его по умолчанию.

Я использую его вмой index.js файл, и он работает правильно.Вот выдержка:

import Food from './food'

[...]

const food = new Food(null, null, null, null, brandName, foodName, calories, protein, carbohydrate, fat)

console.log(food) // instance will be logged -> Works as expected
console.log(Food) // Class will be logged -> Works as expected

Так что пока здесь все работает как положено.Кроме того, я хочу использовать этот класс в другом файле с именем functions.js, чтобы снова передать в него данные, которые я хранил в локальном хранилище (потому что иначе мои методы получения и установки не работают, так как логика пропала).И здесь он больше не работает.

Вот выдержка:

import Food from './food'

console.log(Food) // logs 'undefined' -> is not working as expected

const newFood = new Food(null, null, null, null, 'Schöller', 'Eis', 200, 15, 45, 10)
console.log(newFood) // logs this:
/*
TypeError: _food2.default is not a constructor[Weitere Informationen] functions.js:239:16
./src/functions.js
functions.js:239:16
__webpack_require__
bootstrap:19
./src/food.js
food.js:3
__webpack_require__
bootstrap:19
./src/index.js
index.js:1
__webpack_require__
bootstrap:19
0
http://127.0.0.1:8080/scripts/index-bundle.js:37929:18
__webpack_require__
bootstrap:19
<anonym>
bootstrap:68
<anonym>
http://127.0.0.1:8080/scripts/index-bundle.js:1:11
*/

Файлы организованы так:

enter image description here

Мой webpack.config.js выглядит следующим образом:

const path = require('path')

module.exports = {
    entry: {
        index: ['babel-polyfill', './src/index.js'],
        editFood: ['babel-polyfill', './src/editFood.js'],
        editMeal: ['babel-polyfill', './src/editMeal.js']
    }, 
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: '[name]-bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/, // Regular Expression
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env'],
                    plugins: ['transform-object-rest-spread']
                }
            }
        }]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/scripts/'
    },
    devtool: 'source-map'
}

Я провел некоторые исследования, касающиеся импорта с помощью веб-пакета и так далее, и, насколько я вижу, я импортирую его правильно.Просто чтобы быть уверенным, что я попробовал это с именами экспорта, а также с тем же результатом.Что мне здесь не хватает?Кроме того, я обнаружил некоторые похожие проблемы с сообщением об ошибке, но у них есть проблемы с правильным импортом функции.Я надеюсь, кто-нибудь может дать мне подсказку?

...