1

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.

1
  • I think that if you rename the extension of your file to .mjs it should work. Commented Mar 10, 2021 at 1:09

1 Answer 1

2

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.