我没有任何UI框架。只是一个简单的Nodejs脚本,我需要在其中查询一个GraphQL。
代码:
const ApolloClient = require('apollo-client')
const client = new ApolloClient()错误消息:
TypeError: ApolloClient is not a constructorPackage.json:
{
...
"dependencies": {
"apollo-client": "^2.4.13",
"graphql": "^14.1.1",
"graphql-tag": "^2.10.1"
},
}节点:v8.9.4
我搜索了一段时间,人们有这个问题,主要是因为ApolloClient is no longer in react-apollo. You have to import it from 'apollo-client'
我从apollo-client导入为const ApolloClient = require('apollo-client')
有什么想法吗?谢谢!
发布于 2019-02-14 10:52:34
如果您使用的是require,您可以像这样导入它:
const ApolloClient = require('apollo-client').default或者像这样
const { ApolloClient } = require('apollo-client')否则,您将导入整个模块,该模块本身不是构造函数。
发布于 2019-02-16 10:17:06
对于那些喜欢我使用Node require并且只想让它工作的人来说。
套餐:
npm install graphql apollo-client apollo-cache-inmemory apollo-link-http node-fetch --save
代码:
const fetch = require('node-fetch')
const { createHttpLink } = require('apollo-link-http')
const { InMemoryCache } = require('apollo-cache-inmemory')
const { ApolloClient } = require('apollo-client')
const gql = require('graphql-tag')
const httpLink = createHttpLink({
uri: 'https://api.github.com/graphql',
fetch: fetch
})
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})
const query = gql`
query {
viewer {
login
}
}
`
client.query({
query
}).catch((error) => {
console.log(error)
done()
})响应是错误的,因为您需要添加Authorization: bearer YOURTOKEN来请求标头,但这是另一回事。
多亏了这个answer
发布于 2019-11-02 01:46:50
我有一个相关的问题,虽然使用的是node --experimental-modules,而不是CommonJS。我使用的是apollo-client版本2.6.x和节点版本12.x,所以这可能会改变。
下面是我试图导入它的方式:
import { default as ApolloClient } from 'apollo-client';
const client = new ApolloClient();它不能工作的原因是--experimental-modules仍然导入给定模块的CommonJS版本,即使package.json有指向ESM入口点的"module"字段。这是因为Node 12+中的12+模块支持依赖于package.json中的"type"字段或"Michael脚本“(.mjs)文件扩展名。并且不支持在CommonJS中使用命名导入:js
那么,如何修复呢?有两种方法:
package.json中发布带有package.json字段的ESM包esm这里有一个解决办法:
import apolloClient from 'apollo-client';
const { ApolloClient } = apolloClient;奖金:完整的例子
import nodeFetch from 'node-fetch';
global.fetch = nodeFetch;
import apolloClient from 'apollo-client';
const { ApolloClient } = apolloClient;
import apolloInMemoryCache from 'apollo-cache-inmemory';
const { InMemoryCache } = apolloInMemoryCache;
import apolloHttpLink from 'apollo-link-http';
const { HttpLink } = apolloHttpLink;
const cache = new InMemoryCache();
const link = new HttpLink({
uri
});
const client = new ApolloClient({
cache,
link
});那可不太好。离这里有两条路:
esm加载机制,这不鼓励生态系统从CommonJS切换到本地节点ESM。"type": "module"和esm入口点放置到package.json中的"main"作为一个重大更改。与维护人员一起支持临时兼容性和迁移路径。同时维护ESM的本机版本。https://stackoverflow.com/questions/54688108
复制相似问题