繁体   English   中英

如何在Apollo / GraphQL中使用Styleguidist进行配置

[英]How to configure using Styleguidist with Apollo/GraphQL

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

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

有多种方法可以通过webpack配置Styleguidist,但是我不知道如何使用webpack来使用Apollo。

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')
  }
};

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

通过这种方法,我得到了错误:

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

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

因此,到目前为止(目前)还不能成功使用解决问题的包装器。 因此,我改为从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');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM