运行带有加载程序ts-node/esm.js的节点,要求导入具有.js扩展名 [英] running node with loader ts-node/esm.js requires imports to have the .js extension

查看:52
本文介绍了运行带有加载程序ts-node/esm.js的节点,要求导入具有.js扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的package.json设置为模块来运行节点14:

I am trying to run node 14 with my package.json set as module:

"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';

我知道

ERR_MODULE_NOT_FOUND

ERR_MODULE_NOT_FOUND

但是如果我将其更改为

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

有效.

这是为什么?

推荐答案

如果我们看一下规格,则有

If we take a look at the spec there's this section which states:

当前的说明符分辨率不支持所有默认行为CommonJS加载程序.行为差异之一是自动的文件扩展名的解析和导入目录的能力有一个索引文件.

The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.

还有另一个部分指出:

使用import关键字时必须提供文件扩展名.目录索引(例如'./startup/index.js')也必须完全指定.

A file extension must be provided when using the import keyword. Directory indexes (e.g. './startup/index.js') must also be fully specified.

因此,似乎扩展名实际上是必需的.但是,有选项 -实验说明符分辨率尝试将其设置为-experimental-specifier-resolution = node .

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.

这篇关于运行带有加载程序ts-node/esm.js的节点,要求导入具有.js扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆