【问题标题】:Node.js - SyntaxError: Unexpected token '{'Node.js - SyntaxError: Unexpected token '{'
【发布时间】:2021-03-10 01:07:24
【问题描述】:

我正在尝试使用 ES6 语法。我的代码是这样的,

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  }

这显示以下错误。

[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)

我正在关注documentation。我的语法似乎没问题。出现这种错误的原因是什么?

我也试过import * as keys from './prod';。这给了我SyntaxError: Unexpected token '*'

我的节点版本是 14.15.4。我在 package.json 中使用"type": "module",

【问题讨论】:

  • 我认为如果您将文件的扩展名重命名为 .mjs 它应该可以工作。

标签: node.js ecmascript-6


【解决方案1】:

导入只能处于最高级别。它们被提升(高于所有其他非import 语句),并且不能在块或条件中。

你需要类似的东西

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 }

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2017-11-05
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2019-02-10
    相关资源
    最近更新 更多