简体   繁体   English

无法运行我的 Node.js Typescript 项目 TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts

[英]Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts

When I try to start my app on Heroku I got the following stack trace.当我尝试在 Heroku 上启动我的应用程序时,我得到了以下堆栈跟踪。 It is just a basic ts.app like you see with ts-node and nodemon.它只是一个基本的 ts.app,就像您在 ts-node 和 nodemon 中看到的那样。

I am really interested in what the answer is going to be.我真的很想知道答案是什么。

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

This is my package.json这是我的 package.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"

   }
}

And this is my tsconfig这是我的 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"]
}

Remove "type": "module" from package.json从 package.json 中删除"type": "module"


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


If you don't want to remove "type": "module" (for example if you're using import statements in your.ts which allows the inference of types from modules), then you can use the following option in tsconfig.json :如果您不想删除"type": "module" (例如,如果您在 your.ts 中使用允许从模块推断类型的import语句),那么您可以在tsconfig.json中使用以下选项:

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

And then you can start the server with the config using ts-node .然后您可以使用ts-node使用配置启动服务器。

Install:安装:

npm install -g ts-node

Run:跑:

ts-node my_server.ts

MARCH 2022 2022 年 3 月

USING: Node 16.6.2, ts-node v 10.7.0使用:节点 16.6.2,ts-node v 10.7.0

What worked for me was having "type": "module" in package.json , and adding对我有用的是package.json中的"type": "module" ,并添加

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

tsconfig.json: 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"]
}

Credits to @FelipePlets for the useful answer here感谢@FelipePlets 在这里提供有用的答案

EDIT You may want to use a non- esnext option, as per the ts docs :编辑您可能想要使用非esnext选项,根据ts 文档

The special ESNext value refers to the highest version your version of TypeScript supports.特殊的 ESNext 值是指您的 TypeScript 版本支持的最高版本。 This setting should be used with caution, since it doesn't mean the same thing between different TypeScript versions and can make upgrades less predictable.应谨慎使用此设置,因为它在不同的 TypeScript 版本之间并不意味着相同的事情,并且会使升级更难以预测。

use利用

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

instead of代替

ts-node ./my-script.ts

Solution One解决方案一

  1. Remove "type": "module" from package.json if it's added从 package.json 中删除"type": "module" (如果已添加)
  2. In tsconfig.json under the compilerOptions Set module property to CommonJS module: "CommonJS" and moduleResolution: "Node"tsconfig.jsoncompilerOptions设置模块属性为 CommonJS module: "CommonJS"moduleResolution: "Node"

Solution Two解决方案二

if the first one didn't work, or you have for some reason to keep module: "ESNext"如果第一个不起作用,或者您出于某种原因保留module: "ESNext"

1- Add "type": "module" to package.json 1-将"type": "module"添加到 package.json

2- Install ts-node npm i -g ts-node 2-安装ts-node npm i -g ts-node

3- Go to tsconfig.json and add the following: 3- Go 到tsconfig.json并添加以下内容:

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

4- Run ts-node fileName.ts 4- 运行ts-node fileName.ts

Removing "type": "module" from package.json and adding:package.json删除"type": "module"并添加:

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

In tsconfig.json fixed this for me.tsconfig.json中为我解决了这个问题。

I first came across this problem probably over a year ago, and ts-node has yet to fix it.我大概在一年前第一次遇到这个问题,而 ts-node 还没有解决它。 None of the above solutions worked for me, and I have seemingly tried everything.以上解决方案都不适合我,我似乎已经尝试了一切。

I just resorted to using tsc --outDir out file.ts and then running the file normally with node out/file.js , and then adding out to the .gitignore .我只是求助于使用tsc --outDir out file.ts然后使用node out/file.js file.js 正常运行文件,然后添加out .gitignore

The thought behind ts-node is wonderful, just really sucks when it can't handle seemingly straightforward examples like this. ts-node背后的想法很棒,当它无法处理像这样看似简单的示例时,真的很糟糕。 Apologies the solution doesn't use ts-node, but I couldn't get it to work.抱歉,该解决方案不使用 ts-node,但我无法让它工作。

I made some changes on my package.json & tsconfig.json.Finally, it worked for me!我对我的 package.json 和 tsconfig.json 进行了一些更改。最后,它对我有用!

  1. Add "type": "module" to package.json将“类型”:“模块”添加到 package.json
  2. Uncomment "moduleResolution": "node" section in your tsconfig.json在 tsconfig.json 中取消注释 "moduleResolution": "node" 部分
  3. Change "module" section to "ESNEXT" in your tsconfig.json在 tsconfig.json 中将“模块”部分更改为“ESNEXT”
  4. Then Just Run the main script with this node --loader ts-node/esm.\index.ts然后只需使用此节点运行主脚本 --loader ts-node/esm.\index.ts

tsconfig.json 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. */
}}

package.json package.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"
  }
}

You should be aware of using this command您应该注意使用此命令

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

You can use ts-node-esm instead of ts-node , keeping "type":"module" in package.json, and using import './module.js' in your.ts files.您可以使用ts-node-esm代替ts-node ,在 package.json 中保留"type":"module" ,并在 your.ts 文件中使用import './module.js'

Related: https://github.com/TypeStrong/ts-node/issues/1007相关: https://github.com/TypeStrong/ts-node/issues/1007

UPDATE:更新:

This answer has an even better solution as allows to import modules without.js extension:这个答案有一个更好的解决方案,因为允许导入没有 .js 扩展名的模块:

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

Update: Thanks to some maintainers, a working solution is now officially documented by webpack.更新:感谢一些维护者,webpack 现在正式记录了一个可行的解决方案。 Just take a small look at the official webpack documentation .只需看一下官方webpack 文档即可

The second solution is similar to other answers here and works perfectly fine in my case.第二个解决方案与此处的其他答案类似,在我的情况下工作得很好。

Try adding this to your tsconfig.json尝试将此添加到您的tsconfig.json

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

I was able to fix with a tsconfig.json that looked something like:我能够使用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",
  }
}

before this:在这之前:

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

I had to update ssri我不得不更新 ssri

npm update ssri --depth 5

Not sure if this will help anyone but I fixed it by putting this at the start:不确定这是否会对任何人有所帮助,但我通过将其放在开头来解决它:

#!/usr/bin/env node

I followed advice given herein.我遵循了这里给出的建议。 I also had to uninstall lodash-es and install lodash instead to make it work.我还必须卸载lodash-es并安装lodash以使其正常工作。

Add this to tsconfig.json将此添加到tsconfig.json

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

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

I'm running VS-Code v1.63.2我正在运行 VS-Code v1.63.2

  1. open package.json in your project在您的项目中打开 package.json
  2. You should see a > Debug above 'scripts` (see image)您应该在“脚本”上方看到> Debug (见图)
  3. click on that点击那个
  4. choose script you wish to debug选择要调试的脚本
  5. script will run and stop at first breakpoint脚本将在第一个断点处运行和停止

package.js 中的调试选项

In your package.json {Module:commonJS}, and tsconfig.json {module:commonJS},to ts-node youname.ts在您的 package.json {Module:commonJS} 和 tsconfig.json {module:commonJS} 中,到 ts-node youname.ts

Adding "module": "CommonJS" into tsconfig.json's "compilerOptions" is solved my issue."module": "CommonJS"添加到 tsconfig.json 的 "compilerOptions" 中解决了我的问题。

Ran into this if I'm importing typescript code from a react library but for a backend script, in this case mocha tests.如果我从反应库中导入 typescript 代码但对于后端脚本(在本例中为 mocha 测试),则会遇到此问题。 Its expecting.ts files but finding.tsx files I think.它的expecting.ts 文件,但我认为find.tsx 文件。

In my case I had to move some functions from the.tsx react files into the.ts backend code I was working with.就我而言,我必须将一些函数从 .tsx 反应文件移动到我正在使用的 .ts 后端代码中。

I was trying to run both js and ts files on the same package with "type": "module" set using es6 syntax for imports.我试图在同一个 package 上运行jsts文件,并使用 es6 语法为导入设置"type": "module" Following mysterycommand's answer , installing ts-node package and running ts files with node --loader ts-node/esm worked. 按照神秘命令的回答,安装ts-node package 并使用node --loader ts-node/esm esm 运行ts文件。

July 2022 2022 年 7 月

Node 16.14.2, ts-node 10.8.2节点 16.14.2,ts 节点 10.8.2

First install ts-node and base configuration首先安装 ts-node 和基本配置

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

tsconfig.json: tsconfig.json:

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

You can remove everything related to modules/compilation from package.json.您可以从 package.json 中删除与模块/编译相关的所有内容。

And then you can run your program as然后你可以运行你的程序

ts-node ./main.ts

if your tsconfig.json contains "module": "ESNext".如果您的 tsconfig.json 包含“模块”:“ESNext”。 I have used the below script in my package.json.我在我的 package.json 中使用了以下脚本。 It worked.有效。

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

For me (node version 14), for some reason, the problem was that I install the serialize-error package and when I tried to import it to threw that error.对我来说(节点版本 14),由于某种原因,问题是我安装了serialize-error package 并且当我尝试导入它以抛出该错误时。 To solve it I downgraded the version of the package from 11.0.0 to 8.0.0 .为了解决这个问题,我将 package 的版本从11.0.0降级到8.0.0

If you use PowerShell on VS Code on Windows 11 try to use this command:如果您在 Windows 11 上的 VS Code 上使用 PowerShell,请尝试使用此命令:

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

after this solution: https://stackoverflow.com/a/62099904/8967481在这个解决方案之后: https ://stackoverflow.com/a/62099904/8967481

For anyone who is running into this issue while trying run an script in an NX project.对于尝试在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

I tried to remove this error by following methods but FAILED : 1- Using.mts extension 2- Using type:commonjs instead of type:module in package.json (this will not let you use 'import' in your TS file, However i wanted that, therefore i consider this try to be failed).我尝试通过以下方法消除此错误,但失败了:1- Using.mts 扩展名 2- 在 package.json 中使用 type:commonjs 而不是 type:module(这不会让您在 TS 文件中使用“导入”,但是我想要那个,因此我认为这次尝试失败了)。 3- Restarting the VS-Code 3- 重新启动 VS 代码

Then I tried the following and succeeded: 1- Using --esm flag with ts-node command.然后我尝试了以下并成功了: 1- 将--esm标志与 ts-node 命令一起使用。 eg => npx ts-node --esm./src/index.ts 2 - Inside tsConfig.json, add another option after Compiler options' closing bracket named "ts-node" and set its "esm" option to "true", same as below:例如 => npx ts-node --esm./src/index.ts 2 - 在 tsConfig.json 中,在编译器选项的右括号后添加另一个名为“ts-node”的选项,并将其“esm”选项设置为“true” , 同下:

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

I wanted to use ES modules instead of commonjs in my project.我想在我的项目中使用 ES 模块而不是 commonjs。 In addition to making some changes covered in other answers, the last need step for me was to add this to my compilerOptions in tscongig.json :除了在其他答案中进行一些更改外,我最后需要的一步是将其添加到tscongig.json中的compilerOptions中:

"sourceMap": true,

Running ts-node with --esm worked for me.使用--esm运行ts-node对我有用。

For example:例如:

ts-node --esm src/App.ts

That error is caused by trying to import modules, which without the ES Modules flag, ts-node doesn't support.该错误是由于尝试导入没有 ES 模块标志的模块引起的, ts-node不支持。

@vadimk7 wasn't far off, my solution was to change my file extension to .mts and then use ts-node-esm myfile.mts @vadimk7 离我不远,我的解决方案是将我的文件扩展名更改为.mts ,然后使用ts-node-esm myfile.mts

I removed "type": "module" from package.json and added:我从package.json中删除了"type": "module"并添加了:

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

to tsconfig.js which worked for me.到对我有用的tsconfig.js

changing my改变我的

"moduleResolution": "node", 

to

"moduleResolution": "Node",

in package.json solved this for mepackage.json为我解决了这个问题

I changed my imports from:我改变了我的进口:

import blah from './modules/blah'

to

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法运行 TS 节点 + ES 应用程序 - 获取“ERR_UNKNOWN_FILE_EXTENSION”或“new ERR_MODULE_NOT_FOUND” - Can't run a TS node + ES app - either get `ERR_UNKNOWN_FILE_EXTENSION ` or `new ERR_MODULE_NOT_FOUND` 使用 Typescript 运行 mocha 时抛出:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension &quot;.ts&quot; - Run mocha with Typescript throws: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" ./src/app.ts 中的未知文件扩展名“.ts” - Unknown file extension ".ts" in ./src/app.ts ts-node TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.ts” - ts-node TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.ts” - 再次 - TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" - Again 运行快速服务器,但我收到 TypeError [ERR_UNKNOWN_FILE_EXTENSION] 错误:未知文件扩展名“.ts” - Running express server but I get error of TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.ts”与 mocha - TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" with mocha 类型错误 [ERR_UNKNOWN_FILE_EXTENSION]: - TypeError [ERR_UNKNOWN_FILE_EXTENSION]: TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.json” - TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" Heroku 应用程序因 ERR_UNKNOWN_FILE_EXTENSION 而崩溃 - Heroku app crashes with ERR_UNKNOWN_FILE_EXTENSION
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM