Node.js Typescript 프로젝트 유형 오류 [ERR_UNKNOWN_FILE_EXTENSION]을(를) 실행할 수 없습니다: /app/src/App.ts에 대해 알 수 없는 파일 확장명 ".ts"입니다
내가 헤로쿠에서 앱을 시작하려고 시도했을 때 나는 다음과 같은 스택 추적을 받았다. 이것은 당신이 ts-node와 nodedemon에서 보는 것과 같은 기본적인 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
이것은 나의 소포이다.제이손
{
"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"]
}
패키지에서 제거합니다.제이손
https://github.com/TypeStrong/ts-node/issues/935
https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-1163471306
제거하지 않으려면(예를 들어 모듈에서 형식을 추론할 수 있는 .ts의 문을 사용하는 경우) 의 다음 옵션을 사용할 수 있습니다:
{
"compilerOptions": {
"esModuleInterop": true,
}
}
그런 다음 을 사용하여 구성으로 서버를 시작할 수 있습니다.
설치:
npm install -g ts-node
실행:
ts-node-esm my_server.ts
사용하다
node --loader ts-node/esm ./my-script.ts
// OR
ts-node --esm ./my-script.ts
대신에
ts-node ./my-script.ts
이 전에:
node --loader ts-node/esm ./my-script.ts
나는 ssri를 업데이트해야 했다
npm update ssri --depth 5
저는 아마 1년 전에 이 문제를 처음 접했는데, ts-node는 아직 해결하지 못했습니다. 위의 해결책 중 어떤 것도 나에게 효과가 없었고, 나는 모든 것을 시도해 본 것처럼 보인다.
파일을 사용하여 정상적으로 실행한 다음 에 추가하는 방법에 의존했습니다.
그 이면의 생각은 훌륭합니다. 이렇게 단순해 보이는 예들을 다룰 수 없을 때 정말 최악입니다. 솔루션이 ts-node를 사용하지 않아서 죄송합니다. 하지만 작동하지 못했습니다.
이것이 누군가에게 도움이 될지는 모르겠지만, 나는 처음에 이것을 넣음으로써 그것을 고쳤다:
#!/usr/bin/env node
제거 및 추가:
"compilerOptions": {
"module": "CommonJS"
},
날 위해 이걸 고쳐줬어.
나는 내 소포에 약간의 변경을 가했다.json & tsconfig.json.마침내, 그것은 나에게 효과가 있었다!
- 패키지에 "유형": "모듈"을 추가합니다.제이손
- 주석 "moduleResolution": tsconfig.json의 "node" 섹션
- tsconfig.json에서 "module" 섹션을 "ESNEXT"로 변경합니다
- 그런 다음 이 노드 --loaderts-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. */
}}
포장하다.제이손
{
"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
나는 여기서 주어진 충고를 따랐다. 나는 또한 그것이 작동하도록 하기 위해 대신 제거하고 설치해야 했다.
추가할 파일
{
/* ... your props ... */
"ts-node": {
"compilerOptions": {
"module": "CommonJS"
}
}
}
당신의 소포 안에.json {Module:공통JS} 및 tsconfig.json {module:commonJS}에서 ts-노드 name.ts로 이동합니다
일부 유지 관리자 덕분에 작업 솔루션이 웹 팩에 의해 공식 문서화되었습니다. 관계자를 조금만 봐주세요.
두 번째 솔루션은 여기에 있는 다른 답변과 유사하며 저의 경우에는 완벽하게 잘 작동합니다.
가져오기를 다음에서 변경했습니다:
import blah from './modules/blah'
로.
import blah from './modules.blah.js'
솔루션 1
- 패키지에서 제거합니다.추가되면 json
- 모듈 속성을 CommonJS로 설정 및
솔루션 2
만약 첫 번째 것이 작동하지 않거나 어떤 이유로 당신이 유지해야 한다면
1 - 패키지에 추가합니다.제이손
2 - 설치 노드
3 - 다음으로 이동하여 추가합니다:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
/* ... your props ... */
},
"ts-node": {
"esm": true
}
}
4 - 실행
2022년 3월
사용: 노드 16.6.2, ts-노드 v 10.7.0
나에게 효과가 있었던 것은, 그리고 추가하는 것이었다
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에 대한 크레딧
다음과 같이 비옵션을 사용할 수 있습니다:
특수 ESNext 값은 TypeScript 버전이 지원하는 가장 높은 버전을 나타냅니다. 이 설정은 서로 다른 TypeScript 버전 간에 동일한 의미가 없으며 업그레이드를 덜 예측할 수 있으므로 주의하여 사용해야 합니다.
나의 변화
"moduleResolution": "node",
로.
"moduleResolution": "Node",
나를 위해 이것을 해결했다
패키지에 보관하는 대신 을 사용할 수 있습니다.json 및 .ts 파일에서 사용합니다.
관련:
업데이트:
이 답변은 .js 확장자 없이 모듈을 가져올 수 있는 더 나은 솔루션을 제공합니다:
https://stackoverflow.com/a/65163089/1482990
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
이것을 추가해 보십시오
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node",
}
나는 다음과 같이 보이는 것으로 고칠 수 있었다:
{
"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",
}
}
tsconfig.json에 "모듈"이 포함된 경우: "ESNext". 나는 나의 패키지에 아래의 스크립트를 사용했다.json. 효과가 있었어요.
"start": "nodemon -e ts -w ./src -x npm run watch:serve",
"watch:serve": "node --loader ts-node/esm src/server.ts",
저(노드 버전 14)의 경우, 어떤 이유에서인지 패키지를 설치하고 해당 오류를 발생시키기 위해 패키지를 가져오려고 했을 때 문제가 발생했습니다. 이를 해결하기 위해 패키지 버전을 에서 로 다운그레이드했습니다.
Windows 11의 VS Code에서 PowerShell을 사용하는 경우 다음 명령을 사용해 보십시오:
ts-node-esm.cmd .\my_script.ts
이 솔루션 이후:
프로젝트에서 스크립트를 실행하는 동안 이 문제가 발생하는 모든 사용자를 대상으로 합니다.
# 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
나는 다음 방법을 사용하여 이 오류를 제거하려고 했지만 :1 - 확장자 .mts 사용 2 - 패키지에서 type:module 대신 type:commonjs 사용.json (이것은 당신이 TS 파일에서 '가져오기'를 사용할 수 없게 할 것이지만, 나는 그것을 원했기 때문에, 나는 이 시도가 실패했다고 생각한다.). 3 - VS-Code 다시 시작
그런 다음 다음을 시도하여 성공했습니다. 1 - ts-node 명령과 함께 플래그 사용(예: => npx ts-node --esm ./src/index.ts 2 - Inside tsConfig.json) - 컴파일러 옵션의 닫는 괄호 "ts-node" 뒤에 다른 옵션을 추가하고 "esm" 옵션을 아래와 같이 "true"로 설정하십시오:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
/* ... your props ... */
},
"ts-node": {
"esm": true
}
}
나는 프로젝트에서 commonjs 대신 ES 모듈을 사용하고 싶었다. 다른 답변에서 다루었던 몇 가지 변경 사항 외에도, 제가 마지막으로 필요로 하는 단계는 다음에 추가하는 것이었습니다:
"sourceMap": true,
같이 뛰는 것은 나에게 효과가 있었다.
예:
ts-node --esm src/App.ts
이 오류는 ES Modules 플래그가 없으면 지원되지 않는 모듈을 가져오려고 할 때 발생합니다.
@vadimk7은 멀지 않았고, 내 해결책은 내 파일 확장자를 변경한 다음 사용하는 것이었다
구성을 실험한 결과 다음과 같은 결과가 나왔습니다:
포장하다.제이손
{
"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를 실행하는 데 유용합니다. (및 을 사용하여 실행)
내 생각에는, 이 대답이 가장 좋다.
tldr; 몇 년 동안 일을 만들려고 노력한 후에, 바로 사용할 수 있는 것을 사용하세요.
npm i -D tsx
npx tsx src/index.ts
npm:
- 쓰기 및 상승 시점에 매주 40만 건의 다운로드가 있습니다.
여기 있는 모든 해결책을 시도해 본 결과, 여전히 작동하지 않았다. 그런 다음 실행 스크립트를 에서 로 변경했고 작동했습니다!
'개발하자' 카테고리의 다른 글
쿠버네티스: 내 포드를 확장하는 방법 (0) | 2023.06.18 |
---|---|
주피터 노트북에서 Python을 사용하여 github에서 데이터 가져오기 (1) | 2023.06.17 |
svelte를 사용한 디버깅 (0) | 2023.06.16 |
유형스크립트/자바스크립트에서 별칭을 사용하여 요소 내보내기 (0) | 2023.06.16 |
테라폼 보간에서 문자열에 하위 문자열이 포함되어 있는지 확인하는 방법은 무엇입니까? (0) | 2023.06.15 |