1

我正在尝试使用 GraphQL 为 Styleguidist 填充假数据。我正在使用 Express 制作我的 GraphQL 服务器,但我不确定如何将 Apollo 连接到 Styleguidist?这些示例使用 index.js 文件并将根组件包装在 Apollo 的标签中。

我不确定 Styleguidist 是如何工作的,我不知道 index.js 文件在哪里。

有通过webpack配置Styleguidist的方法,但是不知道怎么用webpack来使用Apollo。

4

2 回答 2

2

Styleguidist 中的每个示例都呈现为一个独立的 React 树,并且 Wrapper 组件根组件,因此您需要像 Redux 示例中所示覆盖它,如下所示:

// lib/styleguide/Wrapper.js
import React, { Component } from 'react';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo';
const client = new ApolloClient({ /* ... */ });
export default class Wrapper extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        {this.props.children}
      </ApolloProvider>
    );
  }
}


// styleguide.config.js
const path = require('path');
module.exports = {
  styleguideComponents: {
    Wrapper: path.join(__dirname, 'lib/styleguide/Wrapper')
  }
};
于 2017-12-02T15:36:20.700 回答
0

所以你可以通过两种方式使用 Styleguidist,一种是使用 Create React App 然后安装一个 NPM Styleguidist 包。然后我发现的另一种方法是从一个示例 github 注册表开始,并随时替换组件。我做了第一个:我使用了 Create React App,所以 Webpack 没有安装在我的主文件夹中,而是在 NPM 模块中使用。

使用这种方法,我得到了错误:

“模块解析失败:意外令牌 (16:6) 您可能需要适当的加载程序来处理此文件类型。”

这意味着我需要配置 Webpack。我没有解决这个问题,但它可能只需要配置 styleguide.config.js 文件以与 Babel 一起使用。(只是猜测)

因此,无法(到目前为止)成功使用解决问题的 Wrapper。因此,我在https://github.com/styleguidist/example下载了 Styleguidist 的示例并重新开始。我不确定有什么区别,但是当我使用包装器时,将 ApolloProvider 包装器添加到页面上的每个组件时效果很好。

要让 Apollo 2 正常工作,您还需要使用 HttpLink 和 InMemoryCache。有一个关于这个的一般设置:https ://www.apollographql.com/docs/react/basics/setup.html 。在创建客户端。

我为我的 GraphQL 服务器使用了不同的端口,因为它在端口 4000 使用 GraphQL/Express 服务器,而 Styleguidist 默认使用端口 6060。所以我做了两件事:将 uri 传递给新的 HttpLink 并在快递服务器允许cors。

Express GraphQl 和 Apollo 服务器中 cors 的参考: https ://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d

所以我的包装文件看起来像:

import React, { Component } from 'react';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

export default class Wrapper extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        {this.props.children}
      </ApolloProvider>
    );
  }
}

我的服务器文件如下所示:

const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');
const cors = require('cors');

const app = express();
app.use(cors());
app.use('/graphql', expressGraphQL({
  schema: schema
  , graphiql: true
}));

app.listen(4000, () => {
  console.log('..listening');
});
于 2017-12-04T23:09:47.323 回答