Nabil Farhan
Nabil Farhan

Reputation: 1536

Node.js - SyntaxError: Unexpected token '{'

I am trying to use ES6 syntax. My code is like this,

if(process.env.NODE_ENV === 'production') {
    import { googleClientID,googleClientSecret,mongoURI,cookieKey  } from './prod';
} else {
    import { googleClientID,googleClientSecret,mongoURI,cookieKey  } from './dev';
}

export { googleClientID,googleClientSecret,mongoURI,cookieKey  }

This is showing the following error.

[0] [nodemon] restarting due to changes...
[0] [nodemon] starting `node index.js`
[0] file:///C:/Projects/emaily/config/keys.js:2
[0]     import { googleClientID,googleClientSecret,mongoURI,cookieKey  } from './prod';
[0]            ^
[0]
[0] SyntaxError: Unexpected token '{'
[0]     at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)

I am following the documentation. My syntax seems ok. What is the reason for an error like this?

I also tried import * as keys from './prod';. This gives me SyntaxError: Unexpected token '*'

My node version is 14.15.4. I am using "type": "module", in package.json.

Upvotes: 1

Views: 10122

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

Imports can only be at the very top level. They're hoisted (above all other non-import statements), and cannot be in blocks or conditionals.

You'll need something like

import * as prod from './prod';
import * as dev from './dev';

const obj = process.env.NODE_ENV === 'production' ? prod : dev;
const { googleClientID, googleClientSecret, mongoURI, cookieKey } = obj;

export { googleClientID, googleClientSecret, mongoURI, cookieKey }

Upvotes: 2

Related Questions