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

标签 javascript ecmascript-6 graphql babeljs

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

_graphql2.default 不是构造函数

这是新的 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
  }
}

我猜编译器期望这段代码是一个类,但它只应该是一个对象文字,我做错了什么?

最佳答案

您基本上转换了此 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'

关于javascript - 将代码从 ES5 转换为 ES6 并导出未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607039/

相关文章:

javascript - ECMAScript 5 'for' 循环,覆盖 'i' 与 ECMAScript 6 'for' 循环

java - 通过查询模式通过子对象访问父对象的 protected 字段

graphql - 是否可以在 GraphQL 查询中使用嵌套/命名空间查询变量?

javascript - 按值|文本查找选择索引

javascript - 悬停时在图像上显示链接

javascript - 用户单击时检测 css 动画中的点

react-native - 如何将 Props 从 Redux Store 传递到 Apollo GraphQL 查询

javascript - 迭代 json 数组以填充下拉列表 - angularjs

css - 错误无法使用 webpack 找到模块

javascript - 查找元素是否存在于 Javascript 数组中