Error: Cannot locate the named export 'remove' in Apollo Client

As I work on developing an apollo client plugin for a Nuxt 3 application, I encountered an error related to a package named 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)

While I suspect the issue has something to do with how Nuxt 3 handles ESM, I cannot confirm it.

Check out the nuxt plugin I created:
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)
})

In a typical situation, I would utilize the nuxt-apollo community module, but it is currently inactive in terms of a nuxt 3 port, hence the need for a custom plugin.

Here are some resources that guided me while creating my plugin:

Answer №1

Resolved by incorporating @apollo/client and ts-invariant/process into the nuxt build transpile configuration in the following manner:

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

Answer №2

After some investigation, I have identified the root cause of the issue. In early 2022, Apollo Client (version 3.5.10) utilizes "module":"index.js" to specify the path of ESM exports. However, it appears that Webpack 5 based bundlers do not support this configuration. Adding exports in the package.json file resolved the issue for me.

If you are facing a similar problem, consider endorsing this feature request.

In the meantime, you can try using a temporary solution like applying a small script to modify the package.json.

Answer №3

Unfortunately, none of the solutions provided were effective in resolving my issue. I found that I also had to include this include statement.

{
    test: /\.m?js$/,
    resolve: {
      fullySpecified: false,
    },
    include: [
      'graphql',
    ].map((name) => new RegExp(`node_modules/${name}`)),
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

The Vue.js countSubcategories() function is designed to return a Promise object

The countSubcategories() function is currently returning [object Promise] instead of the row counts of mapped subcategories. This code snippet uses vue.js and Laravel. Do you have any suggestions on how to fix this issue? <div v-for="(cat,index) in ca ...

Is there a way to navigate to another page once the Facebook.streamPublish() function has finished executing

I am currently facing a challenge with my application where I am able to successfully post a message on a friend's wall using the Facebook.streamPublish() method. However, I also need to save certain details about this post in my database. After send ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

Angular and RxJS work together to repeat actions even when an HTTP request is only partially successful

I am currently attempting to achieve the following: Initiate a stop request using a stored ID in the URL. Send a request with a new ID in the URL and save this new ID. If the response code is 200, proceed as normal. If it is 204, repeat steps 1 and 2 with ...

Encountering an unfamiliar group operator error '$group' in MongoDB

Attempting to calculate the number of distinct (not unique) Emp No in the same department, but encountering an error. Error: Unknown group operator '$group' Code snippet can be found here: https://mongoplayground.net/p/UvYF9NB7vZx db.collectio ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

Node.js Express API returns an error status with an empty array response in a RestFul manner

Currently, I am in the process of developing a RestFull API using Node.JS to validate if a specific license plate is registered in my database (which happens to be MySQL). The endpoint that I have set up for this task is as follows: http://localhost:3009/_ ...

Resetting values in Javascript and JQuery when clicking a button

I've recently implemented a feature on my website header where clicking on the search button reveals a search bar, and clicking on the account button reveals an account bar. With some valuable assistance from Madalin, I was able to achieve this functi ...

Refresh the Page or URL After Submitting a Form using JavaScript or PHP

Just a heads up: I'm fairly new to the world of web development. Currently, I'm in the process of crafting an event calendar using CodeIgniter. However, I've hit a bit of a snag. Whenever I try to update an event using JavaScript, the page ...

What causes my scene to appear black until OrbitControl is activated in ThreeJS?

What causes the scene in ThreeJS to only appear after clicking and moving the cursor? The page remains black until I interact by clicking and moving, then everything shows up. I'm stumped on what the issue could be. Any assistance would be greatly ap ...

Tips for resolving a post 405 error on a Windows 2012 R2 server

My test application is designed to record camera footage and send the file to a directory on my server. The main code for this application is shown below: <!DOCTYPE html> <html> <head> <script src="https://cdn.WebRTC-E ...

Encountering a glitch while attempting to execute my test on webdriverio

Lately, I've encountered an issue while attempting to execute my webdriverio tests following an upgrade of my node version. The error message that now pops up is: 2022-01-11T12:45:05.628Z DEBUG @wdio/config:utils: Couldn't find ts-node package, n ...

JavaScript and the Firefox Scratchpad platform

Currently, I am utilizing the MDN guide for learning JavaScript and experimenting with examples using scratchpad. Here's a scenario: console.log('The value of b is ' + b); var b; Why does the console log display "The value of b is -1"? I ...

BufferGeometry: techniques for rendering face groupings

I have 2 different shapes and 2 sets of patterns. My primary objective is to sometimes hide a portion of the first shape (requiring 2 groups) while simultaneously displaying a section of the second shape (only needing 1 group). Prior to the r72 update, I u ...

Checking if a phone number begins with a zero using a regular expression

Is there a way to ensure that numbers entered into a field always start with a 0? Initially, I thought the company wanted to mandate entering 0 first, but I believe there might be a more elegant solution. function validateNumber(dataValues, setErrors) ...

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Tips on revealing concealed information when creating a printable format of an HTML document

I need to find a way to transform an HTML table into a PDF using JavaScript or jQuery. The challenge I'm facing is that the table contains hidden rows in the HTML, and I want these hidden rows to also appear in the generated PDF. Currently, when I co ...

Activate lighting in Three.js with a simple click

I successfully loaded a sphere mesh with Lambert material. Now, I am trying to add a light source to the point where there is an intersection after clicking. target = object that was clicked. to = vector3 of my click. When the dblclick event listener is ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...