ts-node: 意外的标记 ':'

ts-node: Unexpected token ':'

我正在为我的应用程序编写后端服务器,并决定将 babel-node 执行器更改为 ts-node。我在package.json中的命令是:

"server": "cd server && ts-node --project tsconfig.json -r ts-node/register Server.ts",

但不断出现同样的错误:

> nodejs-server@1.0.0 server D:\Projects\Visual Studio Code\NodeJS Server
> cd server && ts-node --project tsconfig.json -r ts-node/register Server.ts

(node:3824) ExperimentalWarning: The ESM module loader is experimental.
SyntaxError: Unexpected token ':'
    at Loader.moduleStrategy (internal/modules/esm/translators.js:83:18)
    at link (internal/modules/esm/module_job.js:36:21)

我尝试编译一个小文件,但编译器不理解 typescript。

test.ts:

var test: string = 'Hello!';
console.log(test);

我得到同样的错误:

PS D:\Projects\Visual Studio Code\NodeJS Server\server> npx ts-node test.ts
(node:1420) ExperimentalWarning: The ESM module loader is experimental.
SyntaxError: Unexpected token ':'
    at Loader.moduleStrategy (internal/modules/esm/translators.js:83:18)
    at link (internal/modules/esm/module_job.js:36:21)

我已经重新安装了 ts-nodetypescript 模块。

根目录tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "moduleResolution": "Node",
        "traceResolution": false,
        "allowJs": false,
        "esModuleInterop": true,
        "declaration": false,
        "noResolve": false,
        "noImplicitAny": false,
        "removeComments": true,
        "strictNullChecks": false,
        "sourceMap": false,
        "skipLibCheck": true,
        "resolveJsonModule": true,
        "typeRoots": [
            "custom_typings",
            "node_modules/@types",
        ],
    },
    "include": [
        "client",
        "server",
    ],
    "exclude": [
        "node_modules",
        "client/bundle.js"
    ]
}

server/tsconfig.json:

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "module": "CommonJS",
        "jsx": "preserve",
        "noEmit": true,
        "baseUrl": "../",
        "paths": {
            "*": ["node_modules/*"],
            "@server/*": ["server/*"],
            "@client/*": ["client/*"],
            "@routes/*": ["server/routes/*"],
            "@public/*": ["public/*"],
            "@secure/*": ["secure/*"],
            "@utils/*": ["utils/*"],
        },
    },
    "include": ["**/*"]
}

尝试重命名:Server.jsServer.ts

找到解决办法。 在项目配置中(文件package.json)有必要删除模块化工作类型JS。

行:"type": "module",

如果您有 tsconfig,请确保没有为“ESNext”设置任何内容。这可以是 targetmodule 参数。

如果运行它来自命令行,试试这个:

"ts-node -O '{\"module\": \"commonjs\", \"target\": \"ES6\" }' ./path/to/MyFile.ts"

如果这不起作用,放弃 ts-node 并只使用 tsc & node ./dist/MyFile.js