Search code examples
node.jsimportnext.jsapollo-servernodejs-server

issues with imports on modularized apollo server


i have a fully working modularized apollo server on nextJS (based on this article https://www.apollographql.com/blog/modularizing-your-graphql-schema-code-d7f71d5ed5f2/ ) basically im doing an Array of my typedefs and merging the resolvers using the merge function from lodash... so far so good... this feed a function makeExecutableSchema and this schema is going to the server... and it works great...

the problem is im trying to move the server outside nextJS... and when i do try to create a new project and yarn init or npm init... install the dependencies, and try to copy paste all my schema files to the new npm init project ALL my imports are messed up, and i start getting all this errors like:

in nextJS i have (this one simply works in nextJS):

import { merge } from "lodash";

in the new node project it says merge couldnt be found in lodash... or the module is commonJS and it cannot do named imports... or if i do an import using require it says ReferenceError: require is not defined, i think this one should be due to node expecting to run this on a browser but i have no idea how to specify this wont run on a browser since it's simply a js file which intends to modularized the apollo schema...

i just dont understand why all the import sentences work just fine in Next but when im starting the apollo server in plain node every import is giving so many errors... i have fixed some by adding the extension at the end of the filename im importing (thing that was not necessary in nextJS) or by adding "/index" at the end of the package being imported...

Is there a way to make the imports behave like in Next??? but in a new nodeJS project?

Any help or orientation would be GREATLY appreciated


Solution

  • The answer was:

    Use Babel, install with NPM or YARN

    "@babel/core"
    "@babel/node"
    "@babel/preset-env"
    

    add the .babelrc file to the root directory of the project:

    {
      "presets": ["@babel/preset-env"]
    }
    

    to run the main file use a script in package.json like:

    "start": "nodemon --exec babel-node index.js"
    

    and this will allow to execute modern JavaScript :D