[英]ts-node programmatic usage with require('ts-node/register')
[英]ts-node: Unexpected token ':'
我正在為我的應用程序編寫后端服務器,並決定將babel-node executor 更改為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)
我嘗試編譯一個小文件,但編譯器不理解打字稿。
測試.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-node和typescript模塊。
根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"
]
}
服務器/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
找到了解決辦法。 在項目配置(文件package.json )中,有必要刪除工作 JS 的模塊化類型。
行: "type": "module",
如果您有 tsconfig,請確保未將任何內容設置為“ESNext”。 這可以是target
或module
參數。
如果從命令行運行它,試試這個:
"ts-node -O '{\\"module\\": \\"commonjs\\", \\"target\\": \\"ES6\\" }' ./path/to/MyFile.ts"
如果這不起作用,請放棄 ts-node 並使用tsc & node ./dist/MyFile.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.