简体   繁体   中英

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:

"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

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. 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. Directory indexes (eg './startup/index.js') must also be fully specified.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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