source

Node.js Typescript 프로젝트 TypeError [ERR_UNKNOWN_FILE_EXTENTION]: /app/src/App.ts의 알 수 없는 파일 확장자 ".ts"를 실행할 수 없습니다.

itover 2023. 3. 13. 20:25
반응형

Node.js Typescript 프로젝트 TypeError [ERR_UNKNOWN_FILE_EXTENTION]: /app/src/App.ts의 알 수 없는 파일 확장자 ".ts"를 실행할 수 없습니다.

헤로쿠에서 앱을 기동하려고 했을 때, 다음과 같은 스택 트레이스가 표시되었습니다.ts-node와 nodemon에서 볼 수 있는 기본적인 ts.app입니다.

어떤 답이 나올지 정말 궁금해요.

2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting process with command `npm start`
2020-05-30T00:03:14.405285+00:00 app[web.1]: 
2020-05-30T00:03:14.405303+00:00 app[web.1]: > discordtoornamentmanager@1.0.0 start /app
2020-05-30T00:03:14.405303+00:00 app[web.1]: > ts-node src/App.ts
2020-05-30T00:03:14.405304+00:00 app[web.1]: 
2020-05-30T00:03:14.833655+00:00 app[web.1]: (node:23) ExperimentalWarning: The ESM module loader is experimental.
2020-05-30T00:03:14.839311+00:00 app[web.1]: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
2020-05-30T00:03:14.839312+00:00 app[web.1]:     at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
2020-05-30T00:03:14.839314+00:00 app[web.1]:     at Loader.getFormat (internal/modules/esm/loader.js:113:42)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-05-30T00:03:14.839316+00:00 app[web.1]:     at Loader.import (internal/modules/esm/loader.js:178:17)
2020-05-30T00:03:14.847801+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-05-30T00:03:14.847998+00:00 app[web.1]: npm ERR! errno 1
2020-05-30T00:03:14.848957+00:00 app[web.1]: npm ERR! discordtoornamentmanager@1.0.0 start: `ts-node src/App.ts`
2020-05-30T00:03:14.849050+00:00 app[web.1]: npm ERR! Exit status 1
2020-05-30T00:03:14.849172+00:00 app[web.1]: npm ERR! 
2020-05-30T00:03:14.849254+00:00 app[web.1]: npm ERR! Failed at the discordtoornamentmanager@1.0.0 start script.
2020-05-30T00:03:14.849337+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-05-30T00:03:14.854859+00:00 app[web.1]: 
2020-05-30T00:03:14.854998+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-05-30T00:03:14.855069+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-05-30T00_03_14_850Z-debug.log
2020-05-30T00:03:14.907689+00:00 heroku[web.1]: Process exited with status 1
2020-05-30T00:03:14.943718+00:00 heroku[web.1]: State changed from starting to crashed

제 소포입니다.json

{
   "name": "discordtoornamentmanager",
   "version": "1.0.0",
   "description": "",
   "main": "dist/app.js",
   "type": "module",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "dev": "nodemon -x ts-node src/App.ts",
      "start": "ts-node src/App.ts"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
      "@types/node": "^14.0.5",
      "axios": "^0.19.2",
      "discord.js": "^12.2.0",
      "pg": "^8.2.1",
      "reflect-metadata": "^0.1.10",
      "typeorm": "0.2.25",
      "typescript": "^3.9.3",
      "nodemon": "^2.0.4",
      "ts-node": "8.10.1"

   }
}

그리고 이것은 나의 tsconfig입니다.

{
   "compilerOptions": {
      "lib": [
         "es6"
      ],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "dist",
      "resolveJsonModule": true,
      "emitDecoratorMetadata": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "include": ["src/**/*.ts"],
   "exclude": ["node_modules", "**/*.spec.ts"]
}

하다."type": "module"


https://github.com/TypeStrong/ts-node/issues/935

https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-1163471306


하지 않을 "type": "module"를 들어 (을) ,import할 수 )를 하면, 「.ts」의 다음의 할 수 .tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}

,음, 음음음음음음음 and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and 를 사용하여 서버를 시작할 수 .ts-node.

인스톨:

npm install -g ts-node

실행:

ts-node-esm my_server.ts

사용하다

node --loader ts-node/esm ./my-script.ts

대신

ts-node ./my-script.ts

「」의 삭제""type": "module"부에서package.json그리고 추가:추가:

  "compilerOptions": {
    "module": "CommonJS"
  },

인 in intsconfig.json내가 알아서 해.고쳐주셨어요.

2022년 3월

사용방법: 노드 16.6.2, TS 노드 v 10.7.0

What worked for me was having 나에게 효과가 있었던 건"type": "module" in 에package.json 「」를 추가합니다.

node --experimental-specifier-resolution=node --loader ts-node/esm ./src/app.ts

tsconfig.json:

{
    "compilerOptions": {
      "module": "ESNext",
      "esModuleInterop": true,
      "target": "ESNext",
      "moduleResolution": "Node",
      "outDir": "dist",
      "forceConsistentCasingInFileNames": true,
      "noFallthroughCasesInSwitch": true,
      "isolatedModules": false,
      "strict": true,
      "noImplicitAny": true,
      "useUnknownInCatchVariables": false,
      "inlineSourceMap": true
    },
    "ts-node": {
        "esm": true
    },
    "lib": ["esnext"]
}

@FelipePlets에 대한 크레딧은 이쪽에서 유용하게 쓰실 수 있습니다.

편집 다음 중 하나를 사용할 수 있습니다.esnextts docs에 따라 옵션을 설정합니다.

특수 ESNext 값은 사용 중인 TypeScript 버전이 지원하는 가장 높은 버전을 나타냅니다.이 설정은 다른 TypeScript 버전 간에 동일한 것을 의미하지 않으며 업그레이드가 예측 불가능할 수 있으므로 주의하여 사용해야 합니다.

솔루션 1

  1. 하다."type": "module"(되어 있는 경우 (json)
  2. »tsconfig.jsoncompilerOptions으로 설정합니다.JSmodule: "CommonJS" ★★★★★★★★★★★★★★★★★」moduleResolution: "Node"

솔루션 2

안 된로든 계속 사용할 가 있는 ,module: "ESNext"

추가 1- 추가"type": "module"sonjjjjjjj.

- 2 - TS 설치npm i -g ts-node

- 3으로 이동합니다.tsconfig.json다음 항목을 추가합니다.

{
    "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "Node",
        /* ... your props ... */
    },
    "ts-node": {
        "esm": true
    }
}

4-실행ts-node fileName.ts

도 이걸 '아예'에해 보세요.tsconfig.json

"ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node",
}

나는 그 문제를 해결할 수 있었다.tsconfig.json뭇매를 맞다

{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["ES2022"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "ES2022",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
  },
  "exclude": [
    "node_modules",
  ],
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node",
  }
}

이 문제는 약 1년 전에 처음 발견되었지만 TS 노드는 아직 해결하지 못했습니다.위의 솔루션 중 어느 것도 나에게 효과가 없었고, 나는 모든 것을 시도해 본 것 같다.

는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★tsc --outDir out file.ts할 수 있습니다.node out/file.js를하고 나서, 「」를 추가합니다.out.gitignore.

의 이면에 있는 ts-node이런 간단한 예시를 다루지 못할 때는 정말 짜증나죠.죄송합니다. 솔루션에서 TS-노드를 사용하지 않습니다만, 제대로 작동하지 않았습니다.

소포에 변경을 좀 했어요.json 및 tsconfig.json.마침내, 효과가 있었어!

  1. 패키지에 "type": "module"을 추가합니다.json
  2. 언코멘트 "module Resolution" : tsconfig.json의 "node" 섹션
  3. tsconfig.json에서 "module" 섹션을 "ESNEXT"로 변경합니다.
  4. 그런 다음 이 노드 --loader ts-node/esm .\index.ts에서 메인스크립트를 실행합니다.

tsconfig.json

{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Projects */
// "incremental": true,                              /* Enable incremental compilation */
// "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "es5",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve",                                /* Specify what JSX code is generated. */
// "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

/* Modules */
"module": "ESNEXT",  // ****HERE                          /* Specify what module code is generated. */
// "rootDir": "./",                                  /* Specify the root folder within your source files. */
"moduleResolution": "node",   // ****HERE                     /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
// "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true,                        /* Enable importing .json files */
// "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

/* Emit */
// "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
// "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./",                                   /* Specify an output folder for all emitted files. */
// "removeComments": true,                           /* Disable emitting comments. */
// "noEmit": true,                                   /* Disable emitting files from a compilation. */
// "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf",                                /* Set the newline character for emitting files. */
// "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */

/* Interop Constraints */
// "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true,                                      /* Enable all strict type-checking options. */
// "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
// "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
}}

패키지.json

{
"name": "async-with-ts",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"type": "module", // ****HERE
"devDependencies": {
"@types/node-fetch": "^3.0.3",
"ts-node": "^10.2.1",
"typescript": "^4.4.2"
},
"dependencies": {
"node-fetch": "^3.0.0"
  }
}

이 명령어를 사용하는 것에 주의해 주십시오.

node --loader ts-node/esm .\index.ts

하시면 됩니다.ts-node-esmts-node 유지, 유지, 보관"type":"module"포장되어 있습니다.json, 및 사용import './module.js'파일에 ..ts ts ts ts ts 。

관련: https://github.com/TypeStrong/ts-node/issues/1007

갱신:

이 답변에는 .js 확장자를 사용하지 않고 모듈을 Import할 수 있으므로 더 나은 솔루션이 있습니다.

https://stackoverflow.com/a/65163089/1482990

다음 방법으로 이 오류를 제거하려고 했지만 실패: 1- 확장자 2.mts 사용: 패키지 내 type: module 대신 type: commonjs 사용:json(TS 파일에서 'import'를 사용할 수 없습니다.다만, 저는 그것을 원했기 때문에, 이 시도는 실패했다고 생각합니다).3- VS-Code 재부팅

그런 다음 ts-node 명령을 사용하여 --esm 플래그를 사용하였습니다.예를 들어 => npx ts-node --esm ./src / index.ts 2 - Inside tsConfig.json에서 컴파일러 옵션의 닫는 괄호 뒤에 "esm" 옵션을 추가하고 다음과 같이 "esm option"을 true로 설정합니다.

{
    "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "Node",
        /* ... your props ... */
    },
    "ts-node": {
        "esm": true
    }
}

나는 여기에 주어진 조언을 따랐다.또, 언인스톨 할 필요가 있었습니다.lodash-es를 인스톨 합니다.lodash네, 이렇게요.

tsconfig.json에 "module"이 포함되어 있는 경우: "ESNext"package.json에서 아래 스크립트를 사용했습니다.됐다.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

.ts-node--esm날 위해 일했어

예를 들어 다음과 같습니다.

ts-node --esm src/App.ts

는 ES 플래그가 없는 Import하려고 하면 가 Import됩니다.ts-node지원하지 않습니다.

업데이트: 일부 유지보수 담당자 덕분에 현재 웹 팩을 통해 작동 중인 솔루션이 공식적으로 문서화되었습니다.공식 웹 팩 문서를 자세히 살펴보십시오.

두 번째 해결책은 여기 있는 다른 답변과 비슷하며 제 경우에는 완벽하게 작동합니다.

의 경우 이유로 ('14')를 하게 된 였습니다.serialize-error수입하다 패키지 을 이이adedaded운운운운운운에서 .11.0.0로.8.0.0.

윈도우즈 11의 VS 코드에서 PowerShell을 사용하는 경우 다음 명령을 사용해 보십시오.

ts-node-esm.cmd .\my_script.ts

이 솔루션 이후: https://stackoverflow.com/a/62099904/8967481

에서 스크립트를 실행하는 동안 이 문제가 발생한 경우NX프로젝트.

# For apps
ts-node --project tsconfig.app.json $yourFilePath

# For libraries
ts-node --project tsconfig.lib.json $yourFilePath

# For tests
ts-node --project tsconfig.spec.json $yourFilePath

@vadimk7은 멀지 않았습니다.제 해결책은 파일 확장자를.mts그런 다음 사용ts-node-esm myfile.mts

ts-node/puppeteer 구성으로 몇 가지 실험을 한 결과 다음과 같은 결과가 나왔습니다.

패키지.json

{
    "type": "module",
    "scripts": {
        "start": "npx ts-node main.ts"
    },
    ...
}

tsconfig.json

{
    "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" },
    "compilerOptions": {
        "esModuleInterop": true,
        "moduleResolution": "node",
        "module": "ESNext",
        ...
    },
    ...
}

TypeScript 환경에서 Puppeteer를 실행하는 데 적합합니다.
(실행 노드)JS 19.0.0 (TypeScript 4.9.4 및 ts-node 10.9.1)

이 항목을 에 추가합니다.tsconfig.json

{
  /* ... your props ... */

  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

2022년 7월, ts-node 사용

노드 16.14.2, TS 노드 10.8.2

최초 설치 TS 노드 및 기본 구성

npm install ts-node --save-dev
npm install @tsconfig/node16 --save-dev

tsconfig.json:

{
    "extends": "@tsconfig/node16/tsconfig.json",
    "compilerOptions": {
        "resolveJsonModule": true
    },
    "include": [
        "main.ts"
        // here you can include another directories with sources
    ],
    "exclude": [
        "node_modules"
    ]
}

package.json에서 모듈/컴파일과 관련된 모든 것을 삭제할 수 있습니다.

그런 다음 프로그램을 실행할 수 있습니다.

ts-node ./main.ts

저는 프로젝트에서 commonjs 대신 ES 모듈을 사용하고 싶었습니다.다른 답변에 포함된 몇 가지 변경과 더불어 마지막 필요 단계는 이 내용을 제 답변에 추가하는 것이었습니다.compilerOptionstsconfig.json:

"sourceMap": true,

이 전:

node --loader ts-node/esm ./my-script.ts

ssri를 업데이트해야 했다.

npm update ssri --depth 5

이것이 도움이 될지는 모르겠지만, 저는 처음에 이것을 붙여 수정했습니다.

#!/usr/bin/env node

나의 변경

"moduleResolution": "node", 

로.

"moduleResolution": "Node",

포장되어 있습니다.json이 해결해줬어.

당신의 소포 안에.json {모듈:공통JS} 및 tsconfig.json {module:commonJS}, to ts-node yuname.ts

다음에서 Import를 변경했습니다.

import blah from './modules/blah'

로.

import blah from './modules.blah.js'

언급URL : https://stackoverflow.com/questions/62096269/cant-run-my-node-js-typescript-project-typeerror-err-unknown-file-extension

반응형