SyntaxError: Cannot use import statement outside a module

Tags: , , ,

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:

import {startServer} from './server'

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",


2020 Update (Node 13.2.0+)

Verify that you have the latest version of Node installed. The --experimental-modules flag is no longer necessary. Simply do one of the following:

  • Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.


  • 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.

Source: stackoverflow