How to import graphql-upload?

1.5k views Asked by At

I am using the graphql-upload package.

The export section of the package.json file of the graphql-upload package is like this:-

"exports": {
  "./GraphQLUpload.mjs": "./GraphQLUpload.mjs",
  "./graphqlUploadExpress.mjs": "./graphqlUploadExpress.mjs",
  "./graphqlUploadKoa.mjs": "./graphqlUploadKoa.mjs",
  "./package.json": "./package.json",
  "./processRequest.mjs": "./processRequest.mjs",
  "./Upload.mjs": "./Upload.mjs"
},

In my app.js file, I tried to require the graphqlUploadExpress from "graphql-upload/graphqlUploadExpress.mjs" like this:

require("dotenv").config({ path: `./env/.env-${process.env.NODE_ENV}` });
const express             = require("express");
const logger              = require("morgan");
const moment              = require("moment");
const cors                = require("cors");
const path                = require("path");
const bodyParser          = require('body-parser');
const app                 = express();
const fs                  = require("fs");
const { ApolloServer, gql }                   = require("apollo-server-express");
const { mergeGraphQLTypes, mergeResolvers }   = require("@graphql-tools/merge");
const { makeExecutableSchema }                = require("@graphql-tools/schema");
const { applyMiddleware }                     = require("graphql-middleware");
const { graphqlUploadExpress }                = require("graphql-upload/graphqlUploadExpress.mjs"); // <= This is how it is exported
const { createServer }                        = require("http"); // newly added
const { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageLocalDefault } = require("apollo-server-core");
const { WebSocketServer }                     = require("ws");
const { useServer }                           = require("graphql-ws/lib/use/ws");

require("./database/db");
require("./helper/function");
const Stripe = require("./stripe/stripeRoute");
const Cron   = require("./scheduleCron/scheduleCronRoute");
const generateFolder = Helper("generate-folder");

However, I am getting an error like:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
  C:\node-project\parkyt-new-api\server\node_modules
    \graphql-upload\graphqlUploadExpress.mjs
  at Module.load (internal/modules/cjs/loader.js:994:11)
  …more traceback
  (internal/modules/run_main.js:71:12) {code: 'ERR_REQUIRE_ESM'

How do I import graphql-upload?

3

There are 3 answers

0
touri On

Use dynamic imports instead:

 const { default: graphqlUploadExpress } = await import(
   'graphql-upload/graphqlUploadExpress.mjs'
 );

Read more here

0
taylor michels On

I got this working by reverting to v13

yarn add graphql-upload@13

then you can do

const graphqlUploadExpress = require('graphql-upload/public/graphqlUploadExpress.js');
0
Gustavo Andres Benitez On

From versión >= 13 you need to require as:

const graphqlUploadExpress = require("graphql-upload/package"); 

As referencened on their docs