JavaScript - SyntaxError: Unexpected token { 在 Angular Package Format 專案中執行 ts-node 時
我正在嘗試用 ts-node 執行一個 TypeScript 檔案。出現了一個奇怪的錯誤:
import { tes } from "./tes";
^
語法錯誤:意外的標記 { 發生於 Module._compile (internal/modules/cjs/loader.js:720:23)
如果我將專案的 ts 文件複製到一個空目錄中,並且嘗試在沒有任何配置的情況下運行該文件,它可以正常運行,所以問題出在配置上。
我也嘗試生成一個全新的 Angular 套件格式專案:
ng new proj --create-application=false
cd proj
ng g library x
如果我刪除與專案和程式庫相關的所有 tsconfig 檔案,ts-node 就可以正常運行。當我保留它們時,我會遇到同樣的錯誤。
tes 檔案位於 Angular 套件格式庫中。這是頂層的 tsconfig.json:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"es2018",
"dom"
],
"paths": {
"csv": [
"dist/csv/csv",
"dist/csv"
]
}
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
這是專案專用的 tsconfig.lib.json :
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/lib",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": [
"dom",
"es2018"
]
},
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableResourceInlining": true
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}
有什麼想法?
答案#1
看起來你的 tsconfig 設定為使用 esnext 模組輸出 js,而 node 在沒有配置的情況下無法理解這些模組。你可以選擇:
- 從你的
tsconfig.json中移除"module": "esnext",這一行 - 或者,如果你想保留你的 Angular 配置,可以將你的 node 配置為使用新的 ES 模組語法,例如按照這裡的答案操作