Modular Schema Files - Cannot use import statement outside a module

I am following this article to modularize my schema into separate files. I followed the article exactly, but when I try to run things, I get Cannot use import statement outside a module.

Does anybody have any ideas what might be causing this and how to fix it?

Thanks!

To enable ESM modules in a node.js project, add "type": "module" to your package.json.

https://nodejs.org/api/esm.html

Yeah that’s what I thought originally too, but then when I do that, I get…

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/jacobgraf/Sites/project-apollo/graphql.js from /usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js not supported.
Instead change the require of graphql.js in /usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js to a dynamic import() which is available in all CommonJS modules.
    at AwsInvokeLocal.invokeLocalNodeJs (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:818:33)
    at AwsInvokeLocal.invokeLocal (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:245:19)
    at invoke:local:invoke (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:55:47)
    at PluginManager.runHooks (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:573:41)
    at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:611:20)
    at async PluginManager.run (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:672:7)
    at async Serverless.run (/usr/local/lib/node_modules/serverless/lib/Serverless.js:467:5)
    at async /usr/local/lib/node_modules/serverless/scripts/serverless.js:832:9 {
  code: 'ERR_REQUIRE_ESM'
}

@jacobgraf if you control the serverless/lib/plugins/aws/invokeLocal/index.js source and can change it to leverage imports, that should help. Another option is to avoid using ESM / imports in your project-apollo/graphql.js source, and just use require there. That blog post is assuming ESM but you can still modularize your code with other approaches like CommonJS.

1 Like