I've got an ApolloServer project that's giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My "index.js" is:
require('dotenv').config()
import {startServer} from './server'
startServer()
And when I run it I get the error "SyntaxError: Cannot use import statement outside a module". First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the "import" to a "require" and this worked.
But now I have about two dozen "imports" in other files giving me the same error.
*I'm sure the root of my problem is that I'm not even sure what's complaining about the issue. I sort of assumed it was Babel 7 (since I'm coming from Babel 6 and I had to change the presets) but I'm not 100% sure.
Most of what I've found for solutions don't seem to apply to straight Node. Like this one here:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
Says it was resolved by adding "type=module" but this would typically go in the HTML, of which I have none. I've also tried using my project's old presets:
"presets": ["es2015", "stage-2"],
"plugins": []
But that gets me another error: "Error: Plugin/Preset files are not allowed to export objects, only functions."
UPDATE: Here are the dependencies I started with:
"dependencies": {
"@babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",
Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json
file, add the top-level "type"
field with a value of "module"
. This will ensure that all .js
and .mjs
files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs
extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs
extension. All other files, such as .js
will be interpreted as CommonJS, which is the default if type
is not defined in package.json
.