无法识别 ES6 - NodeJS 和 WebStorm

ES6 is not recognized - NodeJS and WebStorm

我一直在谷歌上到处搜索,但找不到答案。

我只是对 Typescript 有点熟悉。开始在我的 GraphQL NodeJS 服务器上工作,并希望使用 Typescript 来更安全、更轻松地编码。

需要做的第一件事是将当前 JS 版本设置为 ES6,我也这样做了。

此外,我这样设置 tsconfig

{
"compilerOptions": {
    "module": "es6",
    "target": "es6",
    "noImplicitAny": false,
    "outDir": "./build",
    "sourceMap": true
},
"exclude": [
    "node_modules"
]

}

我的index.js

import * as express from 'express';
import * as graphqlHTTP from 'express-graphql';
import {Schema} from './src/schema/Schema';

const PORT = 3000;

const app = express();

const graphqlOption: graphqlHTTP.OptionsObj = {
  schema: new Schema().getSchema(),
  pretty: true,
  graphiql: true
};

app.use('/graphql', graphqlHTTP(graphqlOption));

app.listen(PORT, ()=> {
  console.log("listening on PORT 3000");
});

当 运行 我得到

SyntaxError: unexpected token import

此外,当悬停 const graphqlOption: graphqlHTTP.OptionsObj 时,我得到

Types are not supported by the current JavaScript version

请帮忙,我做错了什么?

提前致谢。

编辑:

想要明确一点,当我使用简单的 var express = require('express') 时,我没有得到这个意外的标记,它移到下一行

屏幕截图:

转到:

File -> Settings -> Languages -> JavaScript

并启用 ES6。

问题不在于 WebStorm 或 NodeJS,而是你没有将 ES6 模块声明转换为它们的 ES5 CommonJS 等价物,所以当你 运行 输出时你会得到一个错误,因为没有版本Node 实现了 ES6 模块。

更新您的tsconfig.json

"compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    ...
}

感谢大家的帮助,终于找到问题所在了。 如果你足够仔细地看,你会发现我没有 index.ts 而我试图错误地做的是 运行 index.jsTypescript 语法在里面。

我已将其重命名为 index.ts,使用 tsc 再次创建 build 目录,然后 运行 在那里创建了 index.js,一切有效。

感谢所有评论。