簡體   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