【问题标题】:Apollo Client "Named export 'remove' not found"Apollo 客户端“未找到命名导出‘删除’”
【发布时间】:2022-01-07 01:34:02
【问题描述】:

我正在尝试为Nuxt 3 应用程序创建一个apollo client 插件。它目前正在抛出一个关于名为 ts-invariant 的包的错误:

file:///Users/[my name]/Repositories/[project]/node_modules/@apollo/client/utilities/globals/fix-graphql.js:1
import { remove } from "ts-invariant/process/index.js";
         ^^^^^^
SyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'ts-invariant/process/index.js';
const { remove } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async __instantiateModule__ (file:///Users/[my name]/Repositories/[project]/.nuxt/dist/server/server.mjs:4550:3)
[vite dev] Error loading external "/Users/[my name]/Repositories/[project]/node_modules/@apollo/client/core/index.js".
  at file://./.nuxt/dist/server/server.mjs:3170:289  
  at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:4550:3)

我觉得我对这个错误了解得足够多,知道它与 Nuxt 3 处理 ESM 的方式有关,但我不能确定。

这里是 nuxt 插件:
plugins/apollo-client.js

import { defineNuxtPlugin } from "#app"
import { ApolloClient, InMemoryCache } from "@apollo/client/core"
import { DefaultApolloClient } from "@vue/apollo-composable"

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  const apolloClient = new ApolloClient({
    uri: config.PUBLIC_API_ENDPOINT,
    cache: new InMemoryCache(),
  })
  nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)
})

在正常情况下,我可能会使用 nuxt-apollo 社区模块,但它目前是关于 nuxt 3 端口的,所以它是一个插件。

这是我的插件所依赖的一些文档:
https://v4.apollo.vuejs.org/guide-composable/setup.html#vue-3
https://v3.nuxtjs.org/docs/directory-structure/plugins

【问题讨论】:

标签: javascript vue.js nuxt.js apollo-client nuxtjs3


【解决方案1】:

通过将 @apollo/clientts-invariant/process 包含到 nuxt 构建转译中来解决,如下所示:

  // nuxt.config.js
  // ...
  build: {
    postcss: {
      postcssOptions: require('./postcss.config.js')
    },
    transpile: [
      '@apollo/client',
      'ts-invariant/process',
    ],
  },
  // ...

【讨论】:

    【解决方案2】:

    我想我已经查明了根本问题。 Apollo 客户端(2022 年初撰写本文时为 3.5.10)正在使用 "module":"index.js" 声明 ESM 导出的路径。 然而,基于 Webpack 5 的捆绑器似乎不支持这一点。在 package.json 中使用 exports 对我有好处。

    你应该投票给this feature request

    这是我在那之前的姑息治疗,using a small script to alter the package.json

    【讨论】:

    • 我目前正在使用 Vite 而不是 Webpack,但感谢您的贡献!
    • Vite 开箱即用地处理这个问题?
    猜你喜欢
    • 2020-01-04
    • 2020-11-21
    • 2021-01-04
    • 2020-11-27
    • 2020-05-03
    • 2020-02-27
    • 2017-07-21
    • 2018-09-21
    • 2020-01-05
    相关资源
    最近更新 更多