将代码从ES5转换为ES6并导出未按预期工作

时间:2018-05-30 14:17:59

标签: javascript ecmascript-6 graphql babel

尝试将某些GraphQL代码从ES5转换为ES6时出现以下错误:

_graphql2.default is not a constructor

以下是新的ES6代码:

import GraphQLList from 'graphql'
import ConfigModel from '../../models/config'
import { configType as ConfigType } from '../types/config'

// Query
export default queryType = {
  type: new GraphQLList(ConfigType),
  description: "The configuration for the home 'page'",
  resolve: function () {
    const config = ConfigModel.find()
    if (!config) {
      throw new Error('Error')
    }
    return config
  }
}

ES5代码如下所示:

var GraphQLList = require('graphql').GraphQLList;
var ConfigModel = require('../../models/config');
var ConfigType = require('../types/config').configType;

// Query
exports.queryType = {
  type: new GraphQLList(ConfigType),
  description: 'The configuration for the home \'page\'',
  resolve: function () {
    const config = ConfigModel.find()
    if (!config) {
      throw new Error('Error')
    }
    return config
  }
}

我猜测转换器期望这个代码是一个类,但它只应该是一个对象字面值,我做错了什么?

1 个答案:

答案 0 :(得分:1)

您基本上已转换此ES5行:

var GraphQLList = require('graphql').GraphQLList;

对此:

import GraphQLList from 'graphql'

你应该可以在这里看到错误。

在ES6代码中,GraphQLList将是一个对象,其中包含该模块的所有导出,其中包含一个名为GraphQLList的对象。

所以你可以改变你的ES6代码:

new GraphQLList(ConfigType)

到此:

new GraphQLList.GraphQLList(ConfigType)

或者,作为评论员提到,只需这样做:

import { GraphQLList } from 'graphql'