preloader
心得

How to Build @apollo/client to UMD-standard

How to Build @apollo/client to UMD-standard

My goal is to build @apollo/client to UMD standard so that it can be used to browser extension. I always encounter error messages such as

ERROR in ./node_modules/@apollo/client/react/context/ApolloConsumer.js 2:0-31
Module not found: Error: Can't resolve 'react' in ...(excerpted)
ERROR in ./node_modules/@apollo/client/core/LocalState.js 3:0-40
Module not found: Error: Can't resolve 'graphql' ...(excerpted)

Solution as below:

Prequisites:

  1. You need to install webpack, webpack-cli, and copy-webpack-plugin.

    I use webpack v5.72.1, webpack-cli v4.9.2 and copy-webpack-plugin v9.1.0

  2. You need to follow instructions inside the article: How to Compile a Npm Package to Be Used at Browser Extension

// webpack.config.js

const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");

/**
* copy-webpack-plugin is a plugin of webpack. 
You can know more about it from document: https://webpack.js.org/plugins/
* Notice: Here I doesn't need it. :p
*/

module.exports = {
  mode: "production",
  experiments: {
    outputModule: true,
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].js",
    library: {
      name: "ApolloClient",
      type: "umd",
    },
    iife: true,
  },
  entry: "./node_modules/@apollo/client/core/index.js",
};

Steps

  1. install graphql and react to project’s package.json. They must have be in peerDependancies. Also you can install both of them again to dependencies or devDependencies.

    Below are commands for node v12.15 to peerDependancies:
    yarn add -P [email protected]
    yarn add -P [email protected]

    Below are commands for node v.12.15 to dependencies:
    yarn add [email protected]
    yarn add [email protected]

  2. Use yarn to build @apollo/client version 3.6.4.
    yarn run build
    and its result is put at dist/main.js

  3. Use it with this prefix-format: ApolloClient at code because you declare it as name of library at webpack.config.js.

    /** * If you use it at script section of a html file */
    <script src="./main.js"></script>
    <script type="text/javascript" async>
      const ToLogin = ApolloClient.gql`
        // .....(your own query/mutation plan)
    `;
      // ...(skip)
    
      let client = new ApolloClient.ApolloClient({
        // anything setting you want
      });
    </script>
    

Photo credit to Integrate apollo client in react-native app #1