【问题标题】:Using Babel to Get ApolloClient to ES5 CommonJS Module Format for Node Environment使用 Babel 获取 ApolloClient to ES5 CommonJS Module Format for Node 环境
【发布时间】:2017-03-26 13:18:36
【问题描述】:

使用 Babel 获取 ApolloClient 转 ES5 CommonJS 模块格式

我正在尝试使用 Babel 让 apollo-client 模块在非浏览器节点环境中作为 ES5 工作。我已经完成了下面的步骤,它总是给我相同的结果。我试图弄清楚该结果是否是节点环境的正确结果。当我将 babel 处理的文档导入我的项目并调用应该导出的方法时,我得到,找不到模块。就上下文而言,该项目是一个 fusetools.com 演示。 Fusetools 不支持 ES2015 Promises,所以我们的想法是使用 babel es2015 预设,它应该可以工作。我主要是在追逐这个来学习一些东西,但如果我能让它发挥作用那就太好了。任何以更简单的方式执行此操作的 cmets,现在我更好地理解它,将不胜感激。可以找到我编写代码的项目here。我使用转换后的代码的 fusetools 项目是here

我得到的错误是:

LOG: Error: JavaScript error in MainView.ux line 9: Name: Fuse.Scripting.Error
Error message: require(): module not found: js/apollo-client/ApolloClient.js
File name: MainView.ux
Line number: 9
Source line:        var ApolloClient = require('js/apollo-client/ApolloClient.js'); 

这是我试图达到的代码:

```
"use strict";

var networkInterface_1 = require('./transport/networkInterface');
var isUndefined = require('lodash.isundefined');
var assign = require('lodash.assign');
var isString = require('lodash.isstring');
var store_1 = require('./store');
var QueryManager_1 = require('./core/QueryManager');
var storeUtils_1 = require('./data/storeUtils');
var fragments_1 = require('./fragments');
var getFromAST_1 = require('./queries/getFromAST');
var DEFAULT_REDUX_ROOT_KEY = 'apollo';
function defaultReduxRootSelector(state) {
    return state[DEFAULT_REDUX_ROOT_KEY];
}
var ApolloClient = function () {
    function ApolloClient(_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a,
            networkInterface = _b.networkInterface,
            reduxRootKey = _b.reduxRootKey,
            reduxRootSelector = _b.reduxRootSelector,
            initialState = _b.initialState,
            dataIdFromObject = _b.dataIdFromObject,
            resultTransformer = _b.resultTransformer,
            resultComparator = _b.resultComparator,
            _c = _b.ssrMode,
            ssrMode = _c === void 0 ? false : _c,
            _d = _b.ssrForceFetchDelay,
            ssrForceFetchDelay = _d === void 0 ? 0 : _d,
            _e = _b.mutationBehaviorReducers,
            mutationBehaviorReducers = _e === void 0 ? {} : _e,
            _f = _b.addTypename,
            addTypename = _f === void 0 ? true : _f,
            queryTransformer = _b.queryTransformer;
        this.middleware = function () {
            return function (store) {
                _this.setStore(store);
                return function (next) {
                    return function (action) {
                        var returnValue = next(action);
                        _this.queryManager.broadcastNewStore(store.getState());
                        return returnValue;
                    };
                };
            };
        };
        if (reduxRootKey && reduxRootSelector) {
            throw new Error('Both "reduxRootKey" and "reduxRootSelector" are configured, but only one of two is allowed.');
        }
        if (reduxRootKey) {
            console.warn('"reduxRootKey" option is deprecated and might be removed in the upcoming versions, ' + 'please use the "reduxRootSelector" instead.');
            this.reduxRootKey = reduxRootKey;
        }
        if (queryTransformer) {
            throw new Error('queryTransformer option no longer supported in Apollo Client 0.5. ' + 'Instead, there is a new "addTypename" option, which is on by default.');
        }
        if (!reduxRootSelector && reduxRootKey) {
            this.reduxRootSelector = function (state) {
                return state[reduxRootKey];
            };
        } else if (isString(reduxRootSelector)) {
            this.reduxRootKey = reduxRootSelector;
            this.reduxRootSelector = function (state) {
                return state[reduxRootSelector];
            };
        } else if (typeof reduxRootSelector === 'function') {
            this.reduxRootSelector = reduxRootSelector;
        } else {
            this.reduxRootSelector = null;
        }
        this.initialState = initialState ? initialState : {};
        this.networkInterface = networkInterface ? networkInterface : networkInterface_1.createNetworkInterface({ uri: '/graphql' });
        this.addTypename = addTypename;
        this.resultTransformer = resultTransformer;
        this.resultComparator = resultComparator;
        this.shouldForceFetch = !(ssrMode || ssrForceFetchDelay > 0);
        this.dataId = dataIdFromObject;
        this.fieldWithArgs = storeUtils_1.storeKeyNameFromFieldNameAndArgs;
        if (ssrForceFetchDelay) {
            setTimeout(function () {
                return _this.shouldForceFetch = true;
            }, ssrForceFetchDelay);
        }
        this.reducerConfig = {
            dataIdFromObject: dataIdFromObject,
            mutationBehaviorReducers: mutationBehaviorReducers
        };
        this.watchQuery = this.watchQuery.bind(this);
        this.query = this.query.bind(this);
        this.mutate = this.mutate.bind(this);
        this.setStore = this.setStore.bind(this);
        this.resetStore = this.resetStore.bind(this);
    }
    ApolloClient.prototype.watchQuery = function (options) {
        this.initStore();
        if (!this.shouldForceFetch && options.forceFetch) {
            options = assign({}, options, {
                forceFetch: false
            });
        }
        fragments_1.createFragment(options.query);
        var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
        var realOptions = Object.assign({}, options, {
            query: fullDocument
        });
        delete realOptions.fragments;
        return this.queryManager.watchQuery(realOptions);
    };
    ;
    ApolloClient.prototype.query = function (options) {
        this.initStore();
        if (!this.shouldForceFetch && options.forceFetch) {
            options = assign({}, options, {
                forceFetch: false
            });
        }
        fragments_1.createFragment(options.query);
        var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
        var realOptions = Object.assign({}, options, {
            query: fullDocument
        });
        delete realOptions.fragments;
        return this.queryManager.query(realOptions);
    };
    ;
    ApolloClient.prototype.mutate = function (options) {
        this.initStore();
        var fullDocument = getFromAST_1.addFragmentsToDocument(options.mutation, options.fragments);
        var realOptions = Object.assign({}, options, {
            mutation: fullDocument
        });
        delete realOptions.fragments;
        return this.queryManager.mutate(realOptions);
    };
    ;
    ApolloClient.prototype.subscribe = function (options) {
        this.initStore();
        var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
        var realOptions = Object.assign({}, options, {
            document: fullDocument
        });
        delete realOptions.fragments;
        delete realOptions.query;
        return this.queryManager.startGraphQLSubscription(realOptions);
    };
    ApolloClient.prototype.reducer = function () {
        return store_1.createApolloReducer(this.reducerConfig);
    };
    ApolloClient.prototype.initStore = function () {
        if (this.store) {
            return;
        }
        if (this.reduxRootSelector) {
            throw new Error('Cannot initialize the store because "reduxRootSelector" or "reduxRootKey" is provided. ' + 'They should only be used when the store is created outside of the client. ' + 'This may lead to unexpected results when querying the store internally. ' + "Please remove that option from ApolloClient constructor.");
        }
        this.setStore(store_1.createApolloStore({
            reduxRootKey: DEFAULT_REDUX_ROOT_KEY,
            initialState: this.initialState,
            config: this.reducerConfig
        }));
        this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
    };
    ;
    ApolloClient.prototype.resetStore = function () {
        this.queryManager.resetStore();
    };
    ;
    ApolloClient.prototype.setStore = function (store) {
        var reduxRootSelector;
        if (this.reduxRootSelector) {
            reduxRootSelector = this.reduxRootSelector;
        } else {
            reduxRootSelector = defaultReduxRootSelector;
            this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
        }
        if (isUndefined(reduxRootSelector(store.getState()))) {
            throw new Error('Existing store does not use apolloReducer. Please make sure the store ' + 'is properly configured and "reduxRootSelector" is correctly specified.');
        }
        this.store = store;
        this.queryManager = new QueryManager_1.QueryManager({
            networkInterface: this.networkInterface,
            reduxRootSelector: reduxRootSelector,
            store: store,
            addTypename: this.addTypename,
            resultTransformer: this.resultTransformer,
            resultComparator: this.resultComparator,
            reducerConfig: this.reducerConfig
        });
    };
    ;
    return ApolloClient;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ApolloClient;
//# sourceMappingURL=ApolloClient.js.map
```

感谢我可能从中学到的任何和所有 cmets。谢谢。

【问题讨论】:

    标签: node.js babeljs commonjs graphql-js apollo-server


    【解决方案1】:

    一种方法是像这样使用 webpack:

    const webpack = require('webpack');
    const path = require('path');
    
    module.exports = {
      // watch: true,
      entry: {
        ApolloClient: './config/ApolloClient.js',
        createNetworkInterface: './config/createNetworkInterface.js',
        Redux: './config/Redux.js',
      },
      output: {
        path: path.join(__dirname, 'build/Libs'),
        filename: '[name].js',
        library: '[name]',
        libraryTarget: 'commonjs',
      },
      module: {
        rules: [
          {
            use: 'babel-loader',
            test: /\.js$/,
            exclude: /node_modules/,
          },
        ],
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
      ],
    };
    

    然后在config 目录中你可以拥有:

    /* ApolloClient.js */
    import { ApolloClient } from 'apollo-client';
    
    export default ApolloClient;
    

    /* createNetworkInterface.js */
    import { createNetworkInterface } from 'apollo-client/transport/networkInterface';
    
    export default createNetworkInterface;
    

    如果你也想拥有 Redux:

    /* Redux.js */
    import * as Redux from 'redux';
    
    export default Redux;
    

    但是我无法以这种方式完成gql,不得不使用 bolav 的 fusepm。 您将完全按照 bolav 提到的方式使用它,首先在全球范围内安装它: npm install -G fusepm 然后fusepm npm graphql-tag

    一旦你准备好所有这些,你就可以要求它们如下:

    var Redux = require('build/Libs/Redux');
    var ApolloClient = require('build/Libs/ApolloClient');
    var createNetworkInterface = require('build/Libs/createNetworkInterface');
    var gql = require('fusejs_lib/graphql-tag_graphql-tag.umd');
    

    这种方式仍然可以使用一些 TLC,但现在,它可以工作并完成工作:

    var networkInterface = createNetworkInterface.createNetworkInterface({
      uri: 'http://localhost:8000/graphql',
    });
    
    var client = new ApolloClient.ApolloClient({
      networkInterface,
    });
    
    client.query({
      query: gql`
        query {
          allPosts {
            edges {
              node {
                id
                headline
                summary(length: 80)
                body
                createdAt
                updatedAt
                personByAuthorId {
                  firstName
                  lastName
                }
              }
            }
          }
        }
      `,
    })
    .then(data => data.data.allPosts.edges.forEach(node => pages.add(createPage(node))))
    .catch(error => console.log(error));
    

    另外,如果您喜欢我已经设置了整个项目以及您可能感兴趣的服务器:fuseR

    【讨论】:

      【解决方案2】:

      我制作了fusepm,它有一个模式可以转换 npm 模块以在 FuseTools 下运行它们。它仍然有很多错误,但至少我设法比你更长:

      fuse create app apolloc
      cd apolloc
      npm install apollo-client
      fusepm npm apollo-client
      

      然后在你的javascript中:

      <JavaScript>
          var ApolloClient = require('fusejs_lib/apollo-client.js');
      </JavaScript>
      

      fusepm 使用 Babel,带有一些自定义插件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 2018-10-14
        • 2022-07-06
        • 2015-09-10
        • 1970-01-01
        • 2020-05-30
        • 2020-11-29
        相关资源
        最近更新 更多