简体   繁体   English

使用 loader ts-node/esm.js 运行节点需要导入以具有 .js 扩展名

[英]running node with loader ts-node/esm.js requires imports to have the .js extension

I am trying to run node 14 with my package.json set as module:我正在尝试将 package.json 设置为模块来运行节点 14:

"type": "module",

If I run this command on a typescript file:如果我在打字稿文件上运行此命令:

 node --loader ts-node/esm.mjs --experimental-top-level-await ./src/scripts/ts-build.ts --trace-warnings --experimental-json-modules

and I have extensionless imports like this in a typescript file我在打字稿文件中有这样的无扩展导入

import { logger } from './logger';

I get我得到

ERR_MODULE_NOT_FOUND ERR_MODULE_NOT_FOUND

But if I change it to但是如果我把它改成

import { logger } from './logger.js';

It works.有用。

Why is this?为什么是这样?

If we take a look at the spec there's this section which states:如果我们看一下规范,那么这部分说明:

The current specifier resolution does not support all default behavior of the CommonJS loader.当前的说明符解析不支持 CommonJS 加载器的所有默认行为。 One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.行为差异之一是文件扩展名的自动解析以及导入具有索引文件的目录的能力。

There's another section which states:还有一个部分指出:

A file extension must be provided when using the import keyword.使用 import 关键字时必须提供文件扩展名。 Directory indexes (eg './startup/index.js') must also be fully specified.目录索引(例如'./startup/index.js')也必须完全指定。

So it seems that the extension is actually necessary.所以看起来扩展实际上是必要的。 Howvever, there's the option --experimental-specifier-resolution which you try setting to --experimental-specifier-resolution=node .但是,您可以尝试将选项--experimental-specifier-resolution设置为--experimental-specifier-resolution=node

我在 Node v14.15.0上使用这些实验性功能解决了这个问题。

node --loader ts-node/esm --experimental-specifier-resolution=node your/entry.ts

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM