I am writing a backend server for my app and decided to change babel-node executor to ts-node . My command in package.json is:
"server": "cd server && ts-node --project tsconfig.json -r ts-node/register Server.ts",
But keep getting the same error:
> 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)
I tried compiling a small file, but compiler does not understand typescript.
test.ts :
var test: string = 'Hello!';
console.log(test);
I get the same error:
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)
I have already reinstalled ts-node and typescript modules.
Root 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.js
到Server.ts
Found a solution. In the project configuration (file package.json ) it was necessary to remove the modular type of work JS.
Line: "type": "module",
If you have a tsconfig, make sure nothing is set to "ESNext". This could be either the target
or module
arguments.
If running it from command line, try this:
"ts-node -O '{\\"module\\": \\"commonjs\\", \\"target\\": \\"ES6\\" }' ./path/to/MyFile.ts"
If that doesn't work, ditch ts-node and just use tsc & node ./dist/MyFile.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.